Using HttpURLConnection to send a JSON post reques

2019-08-29 09:23发布

问题:

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;
}
}

回答1:

Try this:

 OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(jsonArrayToPost.toString());


回答2:

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();
}


回答3:

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!