Thursday 27 August 2015

Jersey Content Negotiation


This post is continuation to my previous post. Content negotiation is a mechanism defined in the HTTP specification that makes it possible to serve different versions of a response (like xml, json etc.,) at the same URI.

Till now we are consuming json data and sending json response. But what if another client want to send xml data as input, and get xml data as response. What if some other clinet send some format ‘X’ as input and want some format ‘Y’ as ouput.

How client ask output in specific format
By setting the Accept header.

How client specify specific format of input
By setting Content-Type.

Ex:
Content-Type: application/json
Accept: application/xml

Above headers specifying that client is sending json data as input and expecting xml as response.

What changes I need to do my jersey code
It is very simple, update Produces and Consumes annotations like below.

@Path("employees")
@Produces(value = { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Consumes(value = { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public class EmployeeResource {
                  .....
                  .....
}

If you want some other format supported by jersey, add it as comma separated list.



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment