设置GET请求的正确Content-Length是多少?

19

使用以下代码进行POST请求:

string body = "Hello World";
byte[] bytes = Encoding.ASCII.GetBytes(body);
WebRequest request = WebRequest.Create("http://internalurl");
request.Method = "POST";
request.ContentLength = bytes.Length;

我将内容长度设置为POST的字节数。那么对于GET请求,正确的ContentLength是什么?

1个回答

36

由于通常在进行GET请求时不会发送任何附加数据,因此不应发送头部Content-Length

仅当您发送消息正文时才应包含头部Content-Length,而所讨论的头部的值始终是该字段的长度,以(OCTETs)字节为单位。

(RFC2616) 14.13 Content-Length

Content-Length实体头字段指示发送给接收者的实体正文大小,以十进制OCTETs字节数表示。对于HEAD方法的情况下,它指示将要发送的实体正文的大小,如果该请求是GET,则也是如此。

<snip />

除非第4.4节中的规则禁止使用该字段,否则应用程序应使用此字段来指示消息正文的传输长度。


我所知,当进行GET请求时包含message-body被认为是不好的做法,但是在阅读HTTP RFC2616时,我没有看到任何规定GET请求不能包含message-body

尽管我会假设大多数Web服务器今天不会回复您想要的回复,如果您发送数据并期望在该情况下对其进行解析和处理,则包含message-body

(RFC2616) 4.3 Message Body

The message-body (if any) of an HTTP message is used to carry the entity-body associated with the request or response. The message-body differs from the entity-body only when a transfer-coding has been applied, as indicated by the Transfer-Encoding header field (section 14.41).

   message-body = entity-body
                | <entity-body encoded as per Transfer-Encoding>

Transfer-Encoding MUST be used to indicate any transfer-codings applied by an application to ensure safe and proper transfer of the message. Transfer-Encoding is a property of the message, not of the entity, and thus MAY be added or removed by any application along the request/response chain. (However, section 3.6 places restrictions on when certain transfer-codings may be used.)

The rules for when a message-body is allowed in a message differ for requests and responses.

The presence of a message-body in a request is signaled by the inclusion of a Content-Length or Transfer-Encoding header field in the request's message-headers.

A message-body MUST NOT be included in a request if the specification of the request method (section 5.1.1) does not allow sending an entity-body in requests.

A server SHOULD read and forward a message-body on any request; if the request method does not include defined semantics for an entity-body, then the message-body SHOULD be ignored when handling the request.


2
对这个答案的小补充:RFC7231(RFC723x系列中的一部分,取代了“旧”的RFC2616)简单地指出,“GET请求消息中的有效载荷没有定义的语义;在GET请求上发送有效载荷主体可能会导致某些现有实现拒绝该请求。” - Guillaume
@Filip 如果您有一个以字符串格式表示的JSON内容,那么您会将"Content-Length"设置为json.getBytes("UTF-8")吗?我尝试过这样做,但收到了错误请求 - 无效的内容长度。<hr><p>HTTP错误400。请求中存在无效的内容长度或块长度。</p> - WowBow
3
RFC7230现在明确指出:“当请求消息不包含有效载荷主体且方法语义不预期这样的主体时,用户代理不应发送Content-Length头字段。” - Danio

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