Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jersey - JAX/RS - how to handle different content-type using different handlers

Tags:

jersey

jax-rs

I would like to handle two different media types for the same REST URL using different handlers using Jersey/JAX-RS. Is that possible?

For example:

@Path("/foo")
public class FooHandler {


    @POST
    @Path("/x")
    @Consumes("application/json")
    public Response handleJson() {
    }

    @POST
    @Path("/x")
    @Consumes("application/octet-stream")
    public Response handleBinary() {
    }

}
like image 453
k2k2e6 Avatar asked Feb 05 '15 00:02

k2k2e6


1 Answers

Yes this is possible. There are a lot of things that go into determining the resource method, and the media type is one of them. The client would need to make sure though to set the Content-Type header when sending the request.

If you'd like to learn the exact science behind how the resource method is chosen, you can read 3.7 Matching Requests to Resource Methods in the JAX-RS spec. You can see specificly the part about the media type in 3.7.2-3.b.

Simple test

@Path("myresource")
public class MyResource {
    @POST
    @Path("/x")
    @Consumes("application/json")
    public Response handleJson() {
        return Response.ok("Application JSON").build();
    }
    @POST
    @Path("/x")
    @Consumes("application/octet-stream")
    public Response handleBinary() {
        return Response.ok("Application OCTET_STREAM").build();
    }
}

@Test
public void testGetIt() {
    String responseMsg = target.path("myresource")
            .path("x").request().post(Entity.entity(null, 
                    "application/octet-stream"), String.class);
    System.out.println(responseMsg);

    responseMsg = target.path("myresource")
            .path("x").request().post(Entity.entity(null, 
                    "application/json"), String.class);
    System.out.println(responseMsg);
}

The above test will always print out

Application OCTET_STREAM
Application JSON

like image 94
Paul Samsotha Avatar answered Oct 07 '22 19:10

Paul Samsotha