For some reason I find how to read json data in my cgi script.
I'm sending the json through an android application like this:
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler<String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost(serverUrl + "/cgi-bin/save.py");
JSONObject json = new JSONObject();
try {
SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
String time = sdf.format(camera.getRecordTime().getTime());
json.put("md", camera.isMdOn());
json.put("threshold", camera.getThreshold());
json.put("recordTime", time);
postMethod.setHeader("Content-Type", "application/json");
postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
String response = httpClient.execute(postMethod, resonseHandler);
Log.e("response :", response);
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
and my script is:
#!C:\Python27\python.exe
import cgi, sys, json
#data = cgi.FieldStorage()
#data = sys.stdin.read()
print "Content-type: application/json"
print
response={'result': data['md']}
print(json.JSONEncoder().encode(response))
as you can see I tried several methods (cgi.FieldStorage()
, sys.stdin.read()
)
but nothing works, I'm getting a 500
error. I'm able to send data back from the script but not to read data sent to the script.
I know I can use a framework but I don't want to, so please don't refer me to any of those.