POST 方法是否需要 Accept header,而 return 客户端没有任何内容?

Is Accept header needed for a POST method which doesn't return any content to client?

我有一个端点支持 POST 方法 content-type 作为 json(仅)。但是 POST 请求在其响应 body 中 return 除了状态代码之外没有任何内容。在这种情况下,正确的行为是什么?

  1. 客户端发送 POST 接受 header 作为 application/json
  2. 客户端发送 POST 接受 header 作为 application/xml

在情况2中服务器return应该出错吗?

服务器可能忽略Acceptheader。

如果您在回复中没有返回任何内容,那将毫无意义。由您决定是否要拒绝 Accept header 的请求。

但我想大多数系统不会拒绝这些请求。

RFC 7231 描述了 Accept header

的语义

A request without any Accept header field implies that the user agent will accept any media type in response.

If the header field is present in a request and none of the available representations for the response have a media type that is listed as acceptable, the origin server can either honor the header field by sending a 406 (Not Acceptable) response or disregard the header field by treating the response as if it is not subject to content negotiation.

客户端提供的 Accept header 可能应该反映客户端看到的请求上下文;例如,Web 浏览器可能合理地为 <img><script> 使用不同的 Accept header,在每种情况下都鼓励服务器提供有用的表示。

In the case of a POST,您要协商的是“操作的状态或从中获得的结果”的表示,而不是资源本身的表示。

如果当 media-type 为 application/json 时响应的表示为 zero bytes long,那么我希望当 media-type 时响应的长度也为零字节是 application/xml。所以对我来说接受一个而不接受另一个对我来说并不明显。

https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.2

A request without any Accept header field implies that the user agent will accept any media type in response. If the header field is
present in a request and none of the available representations for
the response have a media type that is listed as acceptable, the
origin server can either honor the header field by sending a 406 (Not Acceptable) response or disregard the header field by treating the
response as if it is not subject to content negotiation.

所以我们可以关闭 2