泽西岛-JAX/RS-如何使用不同的处理程序来处理不同的内容类型 [英] Jersey - JAX/RS - how to handle different content-type using different handlers
问题描述
我想使用Jersey/JAX-RS使用不同的处理程序为同一REST URL处理两种不同的媒体类型.有可能吗?
I would like to handle two different media types for the same REST URL using different handlers using Jersey/JAX-RS. Is that possible?
例如:
@Path("/foo")
public class FooHandler {
@POST
@Path("/x")
@Consumes("application/json")
public Response handleJson() {
}
@POST
@Path("/x")
@Consumes("application/octet-stream")
public Response handleBinary() {
}
}
推荐答案
是可以的.确定资源方法有很多事情,媒体类型就是其中之一.客户端需要确保在发送请求时是否设置Content-Type
标头.
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.
简单测试
@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);
}
以上测试将始终打印
应用程序OCTET_STREAM
应用程序JSON
Application OCTET_STREAM
Application JSON
这篇关于泽西岛-JAX/RS-如何使用不同的处理程序来处理不同的内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!