我保留了完整性的原始答案,但我刚刚查看了
HTTP RFC (2616)第4.3节:
The presence of a message-body in a request is signaled by the inclusion of a Content-Length or Transfer-Encoding header field in the request’s message-headers. A message-body MUST NOT be included in a request if the specification of the request method (section 5.1.1) does not allow sending an entity-body in requests. A server SHOULD read and forward a message-body on any request; if the request method does not include defined semantics for an entity-body, then the message-body SHOULD be ignored when handling the request.
因此,如果您没有内容长度,则必须具有Transfer-Encoding(如果您没有,则应以400状态响应以指示错误请求或411(“需要长度”)).那时,你做转移编码告诉你的:)
现在,如果您正在处理servlet API(或类似的HTTP API),它可能会为您处理所有这些 – 此时您可以使用下面的技术从流中读取,直到它不再产生数据,因为API会处理它(即它不仅仅是一个原始套接字流).
如果您可以向我们提供有关您的上下文的更多信息,那将有所帮助.
原始答案
如果没有内容长度,则表示内容一直持续到数据结束(套接字关闭时).
继续读取输入流(例如,将其写入ByteArrayOutputStream以存储它,或者可能是文件),直到InputStream.read返回-1.例如:
byte[] buffer = new byte[8192];
ByteArrayOutputStream output = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1)
{
output.write(buffer, 0, bytesRead);
}
// Now use the data in "output"
编辑:正如评论中指出的那样,客户端可能正在使用分块编码.通常,您正在使用的HTTP API应该为您处理此问题,但如果您正在处理原始套接字,则必须自己处理它.
关于这是一个请求(因此客户端无法关闭连接)的观点是一个有趣的 – 我认为客户端可能只是关闭发送部分,但我不知道如何映射到TCP中的任何内容在这一刻.我的低级网络知识并非如此.
如果这个答案结果是“绝对没用”,我会删除它……