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

≯℡__Kan透↙ 提交于 2019-12-23 10:08:47

问题


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() {
    }

}

回答1:


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



来源:https://stackoverflow.com/questions/28334113/jersey-jax-rs-how-to-handle-different-content-type-using-different-handlers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!