0

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;
}
}
Farhana Naaz Ansari
  • 7,524
  • 26
  • 65
  • 105
Ayman
  • 11
  • 1
  • 3

3 Answers3

0

Try this:

 OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(jsonArrayToPost.toString());
Varun
  • 214
  • 1
  • 5
  • you should add some more explanation as to what you're doing here – Karan Harsh Wardhan Jan 23 '19 at 05:33
  • It's still giving me true response but the json is not being posted, do you any other alternatives for sending a post request in android? I'm going to try and use Volley and i'll get back to the thread. – Ayman Jan 23 '19 at 20:22
0

you can set inputStream to String:

private String getContent(InputStream inputStream) {
    //将流转换为Stirng ; change to String

    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

    StringBuilder sb = new StringBuilder();

    String line = null;
    try{
        while ((line = reader.readLine()) != null){
            sb.append(line+ "/n");
        }
    }catch (Exception e){
        e.printStackTrace();
    }finally {
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return sb.toString();
}
abby
  • 157
  • 4
0

I was able to point out where the problem was with the help of my colleague who worked on setting up the rest-api. The parameters of my JSON array were wrong and I had to remove the IncidentId... Thank you all for your help!

Ayman
  • 11
  • 1
  • 3
  • Can you elaborate more on how you did resolve this issue – ASghostKI Dec 13 '19 at 15:17
  • The server was supposed to return an error when I sent my JSON, but it kept returning 200 ok which is wrong. I deleted the IncidentId because it wasn't supposed to be there. In any case I ended up using HttpPost library to send my request as it's much easier to handle. – Ayman Jan 16 '20 at 05:41