我正在使用 Jersey (1.18) 为我的 Web 应用程序构建 REST API。在我的部分代码中,我有以下代码片段。
return Response.status(Status.NO_CONTENT).entity(err_message).build();
其中 Status
是 com.sun.jersey.api.client.ClientResponse.Status;
根据 Jersey 文档 NO_CONTENT
应该返回一个 204 代码,而不是这个,http 响应有一个带有 200 代码的 header 。
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
,按预期返回 404 header 。
关于“如何返回 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”,则不要在您的回复中包含内容。
关于java - Jersey 'NoContent' 响应返回 200 而不是 204,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31655486/