ChrisGeo
ChrisGeo

Reputation: 3917

JAX-RS Request specific media type

Lets say I have the following REST method:

@GET
@Path("get/{id}")
@Produces({"application/json", "application/xml"})
public Entity getEntity(@PathParam("id") int id) {
    //do stuff
    Entity entity = find(id);
    return entity;
}

When I hit the rest endpoint with any browser by default I get back XML. Is there a way I can specify at the request which media type I want returned? or must I somehow include that information in the path?

Upvotes: 0

Views: 688

Answers (3)

vinayknl
vinayknl

Reputation: 1252

You have to specify the Accept header with the media type you want in addition to the Content-Type header that states what is the content type of your request.

So use the Accept header instead of Content-Type header:

Accept: application/xml

Upvotes: 1

gowtham
gowtham

Reputation: 987

May be this example can help

RestClientWithAcceptHeader

RestClient client = new RestClient();
    ClientResponse response = client.resource("http://example.com/resources/resource1").header("Accept", "application/json;q=1.0, application/xml;q=0.8").get();
    // find what format was sent back
    String contentType = response.getHeaders().getFirst("Content-Type");

    if (contentType.contains("application/json")) {
        JSONObject entity = response.getEntity(JSONObject.class); /* or use a String, InputStream, or other provider that supports the entity media type */
    } else if (contentType.contains("application/xml") {
        String entity = response.getEntity(String.class); /* or use a JAXB class, InputStream, etc. */

More here and here

Upvotes: 0

Nasonov Nikita
Nasonov Nikita

Reputation: 81

You should manually prepare your response. For example if you want JSON answer, you should convert your Entity class to Json and return String. You can use https://code.google.com/p/google-gson/ for conversion.

In fact it is your decision and your work to prepare the answer. The only thing to take in consideration that Rest works on top of HTTP, so some sort of text(JSON, XML, Plain text) is the most "friendly" format of information.

Upvotes: 0

Related Questions