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