在Android中通过POST方法发送json但总是收到谐振代码400.服务器正常,任务如果在后台执行

时间:2017-06-23 04:33:11

标签: android rest post httpurlconnection

即使我通过AsyncTask在后台运行任务,我仍然会收到错误。

" java.net.ProtocolException:在读取响应后无法写入请求体                                                             在com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:203)"

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

}

1 个答案:

答案 0 :(得分:1)

我已更新您的代码,请尝试此操作

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