Detect end of HTTP request body

Assuming you want your client to work with other servers, and server to work with other clients, your server can’t expect to be treated nicely.

There are two ways to tell when the body has ended. Neither of them require knowledge of the body’s content type as you suggest (e.g., don’t bother looking for </html> — that goes far outside the HTTP protocol).

  1. If the client sends a message with Transfer-Encoding: Chunked, you will need to parse the somewhat complicated chunked transfer encoding syntax. You don’t really have much choice in the matter — if the client is sending in this format, you have to receive it. When the client is using this approach, you can detect the end of the body by a chunk with a length of 0.
  2. If the client instead sends a Content-Length, you must use that.

As you suggest, the third method for detecting the end — when the connection closes — only works for the response, not the request (as then there is no way to send a response).

Leave a Comment