当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Calling getResponseCode on HttpUrlConnection before writing content throws an IOException

问题描述:

I'm trying to implement the following:

  1. Open a POST connection.
  2. Read response code.
  3. Write content.
  4. Read response code.

The second step throws a following exception:

Caused by: java.io.IOException: content-length promised 345286 bytes, but received 0

I understand that 'getResponseCode' will close the writing stream, but i need to find a way of how to read the response code before actually writing anything. I would like to skip the process of writing content to the request body (100 MB) due to the (for an example) 401 code.

网友答案:

HTTP Doesn't work like that. You need to send the full request and only then to read the response code. In your case, your response had promised a request body of 345286 bytes, but you have sent nothing.

The correct way is to do the following:

  1. Open a POST connection.
  2. Write content.
  3. Read response code.

In case you want to verify that the server permits to do it (to avoid 401s) you can add a small GET request first to verify the authentication.

分享给朋友:
您可能感兴趣的文章:
随机阅读: