NeoLiu
NeoLiu

Reputation: 232

Is "Content-Length" or "chunked transfer-encoding" a must for Http request?

Could someone tell me about that Content-Length or Transfer-Encoding: "Chunked" is a must for Http request ? I'm using c++ to write a http sever.

The http respond can use close socket to know the length of message body. But how about request ?

I have checked RFC2616 about http 1.1, but I'm not clear enough about that.

My question is if a http request sent out without "Content-Length" or "Chunked Transfer-Encoding",how could I use "WSARecv" to know the length of message body, for the case I use WSARecv and get all the headers and net stream ends with "\r\n\r\n" coincidentally, I fail to get the length of message body. If I deliver a WSARecv again,it may wait forever because there is no more data. If I do not deliver "WSARecv" again, i may not get the message body after if there has.

Or maybe the "Content-Length" and "chunked transfer-encoding" is a must for http request ? client should set one of them to tell sever the length of message ?

Upvotes: 3

Views: 3812

Answers (2)

Julian Reschke
Julian Reschke

Reputation: 41997

RFC 2616 is obsolete.

The answer is in https://greenbytes.de/tech/webdav/rfc7230.html#header.content-length.

Upvotes: 0

Richard Hodges
Richard Hodges

Reputation: 69854

If you don't specify a Transfer-Encoding or Content-Length then the request (or response) is implicitly a variable length request/response and the only way to signal the end of the body is to shutdown the connection (and conversely detect the shutdown/eof in the receiver).

This means that this kind of request/response is also implicitly Connection: close

If you're implementing HTTP1.1 then you must support all three transfer methods.

When I wrote my HTTP server I abstracted the concept of a "request stream" from the concept of a "connection stream". The "request stream" is polymorphic and supports the concept of reading to "EOF". There's no reason you couldn't also have a method on there to "read_chunk". In the case of a non-chunked request, this could simply read until EOF.

This allowed me to implement simultaneous execution of multiple requests on the same connection (but there is some jiggery-pokery to ensure that the responses go back in the correct order!)

Upvotes: 4

Related Questions