0
votes

I have implemented a RESTful service using Jersey. I am able to return the desired output in JSON format. But, I also need to set Http Status Code and my customized status message. Status code and status message should not be part of the JSON output.

I tried following links:

  1. JAX/Jersey Custom error code in Response
  2. JAX-RS — How to return JSON and HTTP status code together?
  3. Custom HTTP status response with JAX-RS (Jersey) and @RolesAllowed

but I am able to perform only one of the tasks, either returning JSON or setting HTTP status code and message.

I have code something like below:

import javax.ws.rs.core.Response;

public class MyClass(){
@GET
@Produces( { MediaType.APPLICATION_JSON })
    public MyObject retrieveUserDetails()
{
MyObject obj = new MyObject();
//Code for retrieving user details.

obj.add(userDetails);
Response.status(Status.NO_CONTENT).entity("The User does not       exist").build();
return obj; 
}
}

Can anyone provide solution to this?

1

1 Answers

0
votes

the mistakes are :
1. if status is set to NO_content (HTTP204) the norm is to have an entity empty. so entity will be returned as empty to your client. This is not what you want to do in all case, if found return details, if not found return 404.

2.Produces( { MediaType.APPLICATION_JSON }) tells that you will return a json content, and the content of entity is not a json. You will have to return a json. You will see I use jackson as it's part of Jersey.

  1. set a @Path("/user") to set a endpoint path at least at Resource level. Need to set a path in order to adress your resource (endpoint)

  2. use a bean in order to pass multiple things. I've made an example bean for you.

  3. as improvement caution with HTTP return, use the proper one 404 :not found resource 204 : empty.... take a look at the norm: http://www.wikiwand.com/en/List_of_HTTP_status_codes

Take a look the complete code in Gist: https://gist.github.com/jeorfevre/260067c5b265f65f93b3

Enjoy :)