且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java Servlet HttpResponse contentLenght Header

更新时间:2023-12-03 22:36:04

如果实际响应内容长度完全适合响应缓冲区(通常为2KB(取决于服务器make / version / config)),则将设置内容长度标头。但是,如果实际响应内容长度大于响应缓冲区,那么它将比响应内容的结束更快地刷新,那么servlet将使用分块编码并忽略任何设置内容长度标头的尝试。

If the actual response content length fits entirely in the response buffer, which is usually 2KB (it depends on server make/version/config), then the content length header will be set. However, if the actual response content length is larger than the response buffer, so that it would be flushed sooner than the end of response content is reached, then the servlet will send the response with chunked encoding and ignore any attempts to set the content length header.

其中包括 HttpServlet #doGet() 引用如下:

This is mentioned in among others the javadoc of HttpServlet#doGet() which is cited below:


...

...

可能,设置Content-Length标头(使用 ServletResponse.setContentLength(int) 方法),允许servlet容器使用持久连接将其响应返回给客户端,从而提高性能。如果整个响应适合响应缓冲区内,则会自动设置内容长度。

Where possible, set the Content-Length header (with the ServletResponse.setContentLength(int) method), to allow the servlet container to use a persistent connection to return its response to the client, improving performance. The content length is automatically set if the entire response fits inside the response buffer.

使用HTTP 1.1分块编码时(这意味着响应具有Transfer-Encoding标头) ,不要设置Content-Length标题。

When using HTTP 1.1 chunked encoding (which means that the response has a Transfer-Encoding header), do not set the Content-Length header.

...

使用正常编码,数据作为一个连续块发送。

With "normal" encoding, the data is sent as one continuous block.

actualContent

使用分块编码,数据以块状态发送,如下所示

With chunked encoding, the data is sent in chunks which look like this

part1LengthInHexadecimal
actualPart1Content

part2LengthInHexadecimal
actualPart2Content

part3LengthInHexadecimal
actualPart3Content

0

以十六进制表示的部件长度表示客户端下一个数据块的大小(以便它赢得' t意外地解析下一个块作为当前块的一部分)。最后,客户端将各个部分粘合在一起。

The part length in hexadecimal indicates the client how large the next chunk of data is (so that it won't "accidently" parse the next chunk as part of current chunk). Finally, the client glues the parts together.

另请参阅***