Cannot write output after reading input; Experiencing this but not certain of cause

≯℡__Kan透↙ 提交于 2019-12-12 03:04:56

问题


I am experiencing this problem although not sure if exactly.

I have discovered Cannot write output after reading input in logs and, per the above, I believe this is occurring because of a getResponseCode() followed by a getOutputStream().

Would this be the cause of the logged error I am seeing?

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

if(conn.getResponseCode() == 0){
    logger.debug("Success");
} else {                 
    logger.debug("Time out set for 30 seconds");
}
String input = writer.getBuffer().toString();
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());

回答1:


The following code

StringWriter writer = new StringWriter();

String pushURL = "Your URL";

URL url = new URL(pushURL);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setDoOutput(true);

conn.setRequestMethod("POST");

conn.setRequestProperty("Content-Type", "application/restService");

conn.setConnectTimeout(30000);

conn.setReadTimeout(30000);

if(conn.getResponseCode() == 0){
     logger.debug("Success");
} else {                 
 logger.debug("Time out set for 30 seconds");
}

String input = writer.getBuffer().toString();

OutputStream os = conn.getOutputStream();

os.write(input.getBytes());

os.flush();

will result in a java.net.ProtocolException because of the following located here:

The HTTP protocol is based on a request-response pattern: you send your request first and the server responds. Once the server responded, you can't send any more content, it wouldn't make sense. (How could the server give you a response code before it knows what is it you're trying to send?)

So when you call server.getResponseCode(), you effectively tell the server that your request has finished and it can process it. If you want to send more data, you have to start a new request.

Thus, the OP is calling conn.getOutputStream(); after conn.getResponseCode() which is generating the java.net.ProtocolException whose Exception.getMessages() yields

Cannot write output after reading input



来源:https://stackoverflow.com/questions/40852262/cannot-write-output-after-reading-input-experiencing-this-but-not-certain-of-ca

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!