Monday, August 2, 2010

HTTP: Chunked Encoding

In chunked encoding, the content is broken up into a number of chunks; each of which is prefixed by its size in bytes. A zero size chunk indicates the end of the response message. If a server is using chunked encoding it must set the Transfer-Encoding header to "chunked".

Chunked-encoding is not the same as Content-Encoding header. The Content-Encoding header is an entity-body header. since transfer-encodings are a property of the message, not of the entity-body. ("Entity-body" refers to the body or payload [e.g. a JPG image] of an HTTP request [e.g. POST or PUT request] or response).

 

Q: When is chunked encoding really useful?

A: Chunked encoding is useful when a large amount of data is being returned to the client and the total size of the response may not be known until the request has been fully processed. An example of this is generating an HTML table of results from a database query. If you wanted to use the Content-Length header you would have to buffer the whole result set before calculating the total content size. However, with chunked encoding you could just write the data one row at a time back to the client. At the end, you could write a zero-sized chunk when the end of the SQL query is reached.

This is the HTTP header that is sent by the server:

Transfer-Encoding: chunked

In the HTTP 1.1 specification, chunked is the only encoding method supported by the "Transfer-Encoding" header.

 

source

No comments: