Athafoud Athafoud - 7 months ago 22
Java Question

Jersey 'NoContent' response returns 200 instead of 204

I am using Jersey (1.18) to build a REST API for my WebApplication. In a part of my code I have the following snippet.

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


where
Status
is an instance of
com.sun.jersey.api.client.ClientResponse.Status;


According to Jersey Documentation
NO_CONTENT
should return a 204 code, instead of this, the http response has a header with 200 code.


NO_CONTENT

public static final ClientResponse.Status NO_CONTENT

204 No Content, see HTTP/1.1 documentation.


I tried to change the aforementioned code to

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


But the issue still exists.
As a side note, using
NOT_FOUND
instead of
NO_CONTENT
, return a 404 header as expected.

Any suggestion on 'How can I return 204 code?', is this a bug or I am doing something wrong.

Note: Not a duplicate of Returning 200 response code instead of 204

Answer

See this SO answer which says,

...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().

In other words, if you want "NO_CONTENT" then don't include content in your response.