即使我通过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();
}
}
}
答案 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);
}