Iga Koga
Iga Koga

Reputation: 1

Send json via POST method in Android but always receive resonponse code 400. server is ok, task if performed in background

I keep on getting errors even if I run the task in the background via AsyncTask.

"java.net.ProtocolException: cannot write request body after response has been read at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:203) "

pointing to "os = urlConnection.getOutputStream();"

private static void postJsonObject(URL url, JSONObject jsonObject) throws IOException {


    HttpURLConnection urlConnection = null;
    OutputStream os = null;
    BufferedWriter bw = null;

    int responseCode = -1;

    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.connect();

        responseCode = urlConnection.getResponseCode();
        Log.i("Personal", "HTTP URL CONNECTION Response Code: " + responseCode);

        os = urlConnection.getOutputStream();
        bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

        bw.write(jsonObject.toString());

        connectionSuccess = true;

    } catch (IOException e) {
        Log.e("Personal", "Problem sending the json string: ", e);
    } finally {
        if(urlConnection!=null){
            urlConnection.disconnect();
        }
        if(bw!=null){
            bw.close();
        }
        if (os!=null){
            os.close();
        }
    }

}

Upvotes: 0

Views: 97

Answers (1)

Yyy
Yyy

Reputation: 2335

I have updated your code please try this

try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setRequestProperty("Content-Type","application/json");
        urlConnection.setRequestMethod("POST");



        urlConnection.connect();
        os = urlConnection.getOutputStream();
        bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

        bw.write(jsonObject.toString());

        connectionSuccess = true;
        responseCode = urlConnection.getResponseCode();
        Log.i("Personal", "HTTP URL CONNECTION Response Code: " + responseCode);



    } catch (IOException e) {
        Log.e("Personal", "Problem sending the json string: ", e);
    }

Upvotes: 1

Related Questions