Java – get content from HTTP request even without content length header

I'm testing a client that sends me an HTTP request with content but no content length title

How do I extract this content without the help of the contentlength header?

Solution

I kept the original answer for completeness, but I just checked Section 4.3 of HTTP RFC (2616):

Therefore, if you do not have content length, you must have @ R_ 830_ 301 @ (if you do not, respond with 400 status to indicate an incorrect request or 411 ("length required")) At that time, you do transfer coding to tell you:)

Now, if you are working with a servlet API (or a similar HTTP API), it may handle all this for you – at this point, you can use the following technique to read from the stream until it no longer generates data, because the API will process it (that is, it is not just a raw socket word stream)

It would be helpful if you could provide us with more information about your context

Original answer

If there is no content length, the content continues until the end of the data (when the socket is closed)

Continue reading the input stream (for example, writing it to bytearrayoutputstream to store it, or possibly a file) until InputStream Read returns - 1 For example:

byte[] buffer = new byte[8192];
ByteArrayOutputStream output = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1)
{
    output.write(buffer,bytesRead);
}
// Now use the data in "output"

Editor: as pointed out in the comments, the client may be using block coding Generally, the HTTP API you are using should handle this problem for you, but if you are dealing with the raw socket, you must handle it yourself

The idea that this is a request (so the client cannot close the connection) is interesting - I think the client may just close the sending part, but I don't know how to map to anything in TCP at this moment My low-level network knowledge is not so

If the answer is "absolutely useless", I will delete it

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>