29
votes

Is it possible to set the content-length header and also use chunked transfer encoding? and does doing so solve the problem of not knowing the length of the response at the client side when using chunked?

the scenario I'm thinking about is when you have a large file to transfer and there's no problem in determining its size, but it's too large to be buffered completely. (If you're not using chunked, then the whole response must get buffered first? Right??)

thanks.

3

3 Answers

36
votes

1) No: "Messages MUST NOT include both a Content-Length header field and a non-identity transfer-coding. If the message does include a non-identity transfer-coding, the Content-Length MUST be ignored." (RFC 2616, Section 4.4)

2) And no, you can use Content-Length and stream; the protocol doesn't constrain how your implementation works.

11
votes

Well, you can always send a header stating the size of the file. Something like response.addHeader("File-Size","size of the file");
And ignore the Content-Length header.

The client implementation has to be tweaked to read this value, but hey you can achieve both the things you want :)

0
votes

You have to use either Content-Length or chunking, but not both.

If you know the length in advance, you can use Content-Length instead of chunking even if you generate the content on the fly and never have it all at once in your buffer.

However, you should not do that if the data is really large because a proxy might not be able to handle it. For large data, chunking is safer.