泽西 'NoContent' 响应 returns 200 而不是 204

Jersey 'NoContent' response returns 200 instead of 204

我正在使用 Jersey (1.18) 为我的 Web 应用程序构建 REST API。在我的部分代码中,我有以下代码片段。

return Response.status(Status.NO_CONTENT).entity(err_message).build();

其中 Statuscom.sun.jersey.api.client.ClientResponse.Status;

的实例

根据 Jersey 文档 NO_CONTENT 应该 return 一个 204 代码,而不是这个,http 响应有一个 header 和 200码.

NO_CONTENT
public static final ClientResponse.Status NO_CONTENT
204 No Content, see HTTP/1.1 documentation.

我尝试将上述代码更改为

return Response.noContent().entity(err_message).build();

但问题依然存在。 作为旁注,按预期使用 NOT_FOUND 而不是 NO_CONTENT、return a 404 header。

关于 'How can I return 204 code?' 的任何建议,这是一个错误还是我做错了什么。

注意:不是 Returning 200 response code instead of 204

的重复

参见 this SO answer 上面写着,

...204 means "No Content", meaning that the response contains no entity, but you put one in it. It's likely that Jersey is switching it to a 200 for you, which is basically identical to a 204 except that it contains a response entity.

Finally, you can get 204 responses very simply by a couple of built-in behaviors: void methods and null return values both map to a 204 response. Otherwise, simply return Response.status(204).build().

换句话说,如果您想要"NO_CONTENT",则不要在您的回复中包含内容。

经过进一步挖掘,我发现了问题所在。 W3c Documentation给出提示。

我在引用

10.2.5 204 No Content

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent's active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent's active view.

The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.

在我的代码中有 entity(err_message) 导致了问题。通过删除它 204 正确返回。我认为 Jersey 或 'someone' 以某种方式将响应投射到 200 因为它有内容。

更新 (02/05/2015)

这个 blog post link(post今天早些时候作为答案编辑,然后被删除)提供了一些关于情况的额外见解。根据博客 post 的内容,只要 HTTP 响应中有任何内容,就会调用以下方法。此方法将状态代码设置回 200。

private void commitWrite() throws IOException {
   if (!isCommitted) {
       if (getStatus() == 204)
           setStatus(200);
       isCommitted = true;
       o = responseWriter.writeStatusAndHeaders(size, ContainerResponse.this);
   }
}

我们可以说 Jersey 检测到由于响应中有一些内容,状态代码被错误地设置为 204 并将其更改为适当的 200。