ContentType头是否适用于除PUT或POST之外的任何HTTP谓词?

2024-09-26 17:54:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在试用CollectionSpace软件的REST API,注意到将Content-Type标头作为GET请求的一部分发送会导致以下错误:

HTTP Status 415 - Cannot consume content type

我尝试过的两个pythonrest客户机库,github上的restclient和google代码上的pythonrest client,在发出GET请求时都会发送一个Content-Type头。在

我从查看http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html得到的理解是,客户机应该只在POST和PUT请求上发送内容类型的头。对吗?在

这两个库都发送了头,这一事实使我认为服务器通常会忽略它,而不是返回客户端错误代码。在


Tags: restapihttpget软件typestatus错误
2条回答

415无法使用内容类型

如果REST资源有@consumers建议接受特定的MIME类型,则会出现此问题。要解决此问题,请在请求/资源调用中设置正确的“Accept”头和“Content Type”头。对于RESTEasy的MockHttpRequest,可以简单地

在请求.接受(MediaType.APPLICATION_JSON); 请求.contentType(MediaType.APPLICATION_JSON)

虽然在规范中没有明确的概述,但是可以做出一些推断。Section 7.2.1状态

Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body.

这很明显,也很有道理。鉴于此,我们可以查看一下Section 9(方法定义),看看哪些定义提到它们可能在请求主体中有一个实体。提到他们三个:

选项

If the OPTIONS request includes an entity-body (as indicated by the presence of Content-Length or Transfer-Encoding)...

...used to request that the origin server accept the entity enclosed in the request...

放置

...requests that the enclosed entity be stored under the supplied Request-URI

有一种方法特别禁止实体TRACE:

A TRACE request MUST NOT include an entity.

实际上,您可以发送任何在主体中包含实体和内容类型头的方法(TRACE除外)。但是,根据规范,除非是上面三种方法中的一种,否则我不希望服务器使用它。在


我还想说,您使用的响应HTTP状态415的软件违反了规范。在

Section 4.3说:

...if the request method does not include defined semantics for an entity-body, then the message-body SHOULD be ignored when handling the request.

由于规范不包括带有GET请求的实体体的定义语义,服务器应该忽略它。在

另外,如果请求中没有提供实体,并且内容长度为零(假设未设置传输编码标头且不是“标识”),则服务器不应尝试使用实体,而不管请求方法或是否存在内容类型标头。这可以通过确定Section 4.4中描述的消息长度的优先顺序进行备份。在

相关问题 更多 >

    热门问题