0

I'm using JAX-RS and I want to display the HTTP status and an error message.

Example: HTTP 204 No Content

Here is my code:

public Response getMessageById(@Context HttpServletRequest request, 
 @PathParam("idMessage") BigInteger idMessage){
 if (idMessage== null){
        return Response.status(HttpURLConnection.HTTP_NO_CONTENT)
               .entity("No Content").build(); 
    }
 }

It displays No Content without the HTTP status.

1 Answer 1

1

HTTP defines a response header and a response body. The latter one is set by calling entity(), the former by status(). So what you actually send is this:

204 No Content

No Content

You just don't see the header if the tool you use does not display it by default. Use for example curl -v http://your-rest-service/api/resource so see it.

Furthermore:

  • Don't return 204 if an id is missing. This would rather be a 400 or 404 depending on the sematics. 204 is for operations that don't need to return anything (like PUT, POST, DELETE).
  • I doubt that this parameter can be null. JaxRS will not select the method if the request does not match the @Path.
  • Although using the constants in HttpURLConnection is possible, it would be more consistent to use javax.ws.rs.core.Response.Status
  • HttpServletRequest is for rare edge cases only. Don't use it if you don't need it.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.