java.net.ProtocolException: 在哪里读取输入?

java.net.ProtocolException: where is input being read?

我查看了多篇关于此问题的帖子,其中 most/all 的代码尝试在输出流之前创建输入流。我明白了。我不认为我在这里这样做。错误之前我的输入流是在哪里创建的?

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
// ...

来自 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

所以基本上你需要在 OutputStream 之后写 你已经手动打开了与资源的连接,而不考虑哪些标志或设置是设置在那个过程中。那不行。

实际上,您甚至不应该自己调用方法 connect(),因为依赖于连接的方法,例如 getInputStream()getOutputStream() 已经存在如果需要,将执行连接

删除行 conn.connect().