是否需要 HTTPPUT 请求来包含主体?

我在标准中找不到这个的明确规格。我有一个 HTTP 客户端,它在执行 PUT 请求时没有包含 Content-Length: 0头,我没有指定主体,还有一个服务器被这样的请求搞糊涂了,我想知道我应该责怪哪个程序。

134041 次浏览

The content length field is required as per the following section in the HTTP/1.1 standard http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13

What is being PUT (in the verb sense) onto the server if there's no content? The spec refers to the content as "the enclosed entity", but a request with no content would have no enclosed entity, and therefore nothing to put on the server.

Unless, of course, you wanted to PUT nothing onto the server, in which case you'd probably want a DELETE instead.

HTTP requests have a body if they have a Content-Length or Transfer-Encoding header (RFC 2616 4.3). If the request has neither, it has no body, and your server should treat it as such.

That said it is unusual for a PUT request to have no body, and so if I were designing a client that really wanted to send an empty body, I'd pass Content-Length: 0. Indeed, depending on one's reading of the POST and PUT method definitions (RFC 2616 9.5, 9.6) one might argue that the body is implied to be required - but a reasonable way to handle no body would be to assume a zero-length body.

Not answering the question, but asserting how jaxrs allows me to frequent use of bodyless PUTs:

Example of bodyless put: Give user an additional permission.

PUT /admin/users/{username}/permission/{permission}

A body is not required by the IETF standard, though the content-length should be 0 if there's no body. Use the method that's appropriate for what you're doing. If you were to put it into code, given

int x;
int f(){ return x; }

and a remote variable called r.

A post is equivalent to

r=f();

A put is equivalent to

r=x;

and a get is equivalent to

x=r;