I've looked at multiple posts with this issue, and most/all of them have code that tries to create an inputstream before an outputstream. I get that. I didn't think I was doing that here. Where is my inputstream being created before the error?
URL url = new URL(myURL);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
// Grab, configure json input as myInput
// ...
byte[] input = myInput.getBytes();
conn.connect();
// Write as post body
try(OutputStream os = conn.getOutputStream()) {
os.write(input); // <-- java.net.ProtocolException Error "Cannot write output after reading input" here
}
// Attempt to read response using InputStream
// ...
CodePudding user response:
From the documentation of URLConnection::connect()
Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.
If the connect method is called when the connection has already been opened (indicated by the connected field having the value true), the call is ignored.
URLConnection objects go through two phases: first they are created, then they are connected. After being created, and before being connected, various options can be specified (e.g., doInput and UseCaches). After connecting, it is an error to try to set them. Operations that depend on being connected, like getContentLength, will implicitly perform the connection, if necessary
So basically you're requiring to write in the OutputStream
after you have manually opened the connection to the resource, without taking care of which flags or settings are set on that process. That won't work.
Actually, you shouldn't even call the method connect()
by yourself, since the methods that depend on being connected, like getInputStream()
and getOutputStream()
already will perform the connection if they need to.
Remove the line conn.connect()
.