在服务器响应中不包含Content-Length头会导致什么后果?

9

RFC指出,content-length头部是可选的(“..应用程序应使用此字段...”)。

据我所知,如果不包含此头部,则客户端将无法知道期望接收多少数据,因此在下载正文(即顶部而不是底部的进度条)时无法显示确定性进度条。

progress

1个回答

16

我认为你隐含的问题是“客户端如何检测HTTP消息的结束?”请参阅RFC 7230 - HTTP/1.1 Message Syntax and Routing - Message Body Length

消息主体的长度由以下任一条件(按优先顺序)确定:

  1. 对于HEAD请求的任何响应以及状态码为1xx(信息性状态码)、204(无内容)或304(未修改)的任何响应,始终通过在标头字段之后的第一个空行终止,并因此不能包含消息主体。
  1. 对于连接请求的任何成功响应都意味着连接将立即在终止标头字段的空行后成为隧道。客户端必须忽略在这样的消息中收到的任何Content-Length或Transfer-Encoding标头字段。
  1. 如果存在Transfer-Encoding标头字段并且分块传输编码(第4.1节)是最终编码,则通过读取和解码分块数据直到传输编码指示数据完整,来确定消息主体的长度。

  If a Transfer-Encoding header field is present in a response and
   the chunked transfer coding is not the final encoding, the
   message body length is determined by reading the connection until
   it is closed by the server.  If a Transfer-Encoding header field
   is present in a request and the chunked transfer coding is not
   the final encoding, the message body length cannot be determined
   reliably; the server MUST respond with the 400 (Bad Request)
   status code and then close the connection.
  If a message is received with both a Transfer-Encoding and a
   Content-Length header field, the Transfer-Encoding overrides the
   Content-Length.  Such a message might indicate an attempt to
   perform request smuggling (Section 9.5) or response splitting
   (Section 9.4) and ought to be handled as an error.  A sender MUST
   remove the received Content-Length field prior to forwarding such
   a message downstream.
如果接收到的消息没有传输编码(Transfer-Encoding)且具有多个Content-Length头字段具有不同的字段值或单个Content-Length头字段具有无效值,则消息分帧无效,接收方必须将其视为不可恢复的错误。如果这是一个请求消息,则服务器必须响应400(Bad Request)状态代码,然后关闭连接。如果这是代理收到的响应消息,则代理必须关闭与服务器的连接,丢弃接收到的响应,并向客户端发送502(Bad Gateway)响应。如果这是用户代理接收到的响应消息,则用户代理必须关闭与服务器的连接并丢弃接收到的响应。 如果存在有效的Content-Length头字段而没有传输编码,则它的十进制值定义了以八位字节为单位的预期消息正文长度。如果发送者在接收指示的八位字节数之前关闭连接或接收方超时,则接收方必须将消息视为不完整并关闭连接。 如果这是一个请求消息且以上情况均不成立,则消息正文长度为零(不存在消息正文)。 否则,这是一个没有声明消息正文长度的响应消息,因此消息正文长度由服务器关闭连接之前接收到的八位字节数确定。 当服务器省略Content-Length头时,它必须使用其他机制来指示消息的结束。 因此,回答您的问题:场景3(分块)和7(读取直到服务器关闭连接)是客户端不知道长度的场景。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接