End of an HTTP Response

2019-01-28 10:43发布

问题:

What indicates the end of an HTTP Response, without having a Content-Length header?

I've read that in some case, that server closes the TCP connection. But I've witnessed cases that the TCP Connection existed after receiving all the response.

So a major problem arises when:

  • There isn't a Content-Length header
  • TCP connection exist after receiving all of the HTTP Response
  • The browser wishes to use the same TCP connection in order to send more HTTP Requests

In that case, how the browser knows it can use the same TCP connection? The server might send more content that's relevant to the 1'st HTTP Request and that would get mixed up with the 2'nd HTTP Response.

回答1:

If both the client and the server support HTTP 1.1, and the server does not know the response body size in advance (and therefore cannot send the Content-Length response header), the server should use chunked encoding, which allows the client to find the end of the response body even if the server does not close the TCP connection immediately after sending the response.

If HTTP 1.1 cannot be used (because either the client or the server is too old), the chunked encoding cannot be used, and in such cases sending a response without the Content-Length header prevents the server from keeping the TCP connection persistent.