java.net.ProtocolException: Cannot write output after reading input.

习惯步行 发布于 2016/11/11 11:31
阅读 866
收藏 0
public String submitPost(HashMap<String, Object> map, String surl)
throws Exception {


StringBuffer responseMessage = new StringBuffer();


StringBuffer params = new StringBuffer();


Iterator<Entry<String, Object>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Object> element = it.next();
params.append(element.getKey());
params.append("=");
params.append(element.getValue());
params.append("&");
}


if (params.length() > 0) {
params.deleteCharAt(params.length() - 1);
}


URL url = new URL(surl);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);


conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length",
String.valueOf(params.length()));
conn.setDoInput(true);


conn.connect();
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(),
"UTF-8");
out.write(params.toString());
out.flush();


int code = conn.getResponseCode();
if (code != 200) {
out.close();
return " ERROR";
} else {
int charCount = -1;
InputStream in = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in,
"UTF-8"));
while ((charCount = br.read()) != -1) {
responseMessage.append((char) charCount);
}
String res = "";
//if (responseMessage.toString().length() > 10)
//res = responseMessage.toString().substring(0, 10);
//else
res = responseMessage.toString();
in.close();
br.close();
out.close();
conn.disconnect();
return res;
}


}

错误信息:

java.net.ProtocolException: Cannot write output after reading input.
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1278)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1257)
at com.msg.callback.HttpPostIpml.submitPost(HttpPostIpml.java:124)
at com.elan.testmq.Work.dealQueue(Work.java:75)
at com.elan.testmq.Work.dealInit(Work.java:54)
at com.elan.testmq.Work.run(Work.java:19)

加载中
返回顶部
顶部