I'm new to Android development and I'm trying to send a post request with a JSON body using HttpURLConnection. Using Postman or python will successfully post the data to the rest api, but for some reason i'm unable to post the JSON Array in android studio even though I get no errors... The server actually returns true(Which is supposed to happen) which I think that the connection is being made (i'm getting 200 response code) but posting the JSON never happens.
Would someone be able to help me find out if the post makes it to the api? It would be much appreciated
JSON FORMAT:
[ { "timeOfEvent": "2019-01-23T02:00:56", "incidentId": 473, "description": "testing tweet #4", "incidentTypeId": 1, "source": "Twitter", "user": null, "url": null, "sourceId": "1087892909335199745" } ]
public class postJsonTask extends AsyncTask<String,String,JSONObject> {
@Override
protected JSONObject doInBackground(String... params){
Log.i("postJSONTask","Beginning of doInBackGround");
JSONObject jsonToPost = new JSONObject();
JSONArray jsonArrayToPost = new JSONArray();
HttpURLConnection conn = null;
try {
URL url = new URL("my url goes here");
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(15*1000);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
jsonToPost.put("timeOfEvent", "2019-01-21T09:10:10");
jsonToPost.put("incidentId", 1);
jsonToPost.put("description", "Ayman Testing data");
jsonToPost.put("incidentTypeId", 1);
jsonToPost.put("source", null);
jsonToPost.put("user", null);
jsonToPost.put("url", null);
jsonToPost.put("sourceId", null);
jsonArrayToPost.put(jsonToPost);
OutputStreamWriter streamWriter = new OutputStreamWriter(conn.getOutputStream());
Log.i("postJSONTask","Conn.getOutputStream "+ conn.getOutputStream().toString());
Log.i("postJSONTask","Trying to post: "+ jsonArrayToPost.toString());
streamWriter.write(jsonArrayToPost.toString());
streamWriter.flush();
streamWriter.close();
StringBuilder stringBuilder = new StringBuilder();
Log.i("postJSONTask, message",conn.getResponseMessage());
Log.i("postJSONTask respoCode", String.valueOf(conn.getResponseCode()));
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStreamReader streamReader = new InputStreamReader(conn.getInputStream());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String response = null;
while ((response = bufferedReader.readLine()) != null) {
stringBuilder.append(response + "\n");
}
bufferedReader.close();
Log.d("postJSONTask response", stringBuilder.toString());
} else {
Log.e("postJSONTask error", conn.getResponseMessage());
return null;
}
} catch (Exception e) {
Log.e("postJsonTask error", e.toString());
return null;
}
finally{
conn.disconnect();
}
return null;
}
}