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() {
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With