Resteasy Content-Type defaults
I'm writing an app using Resteasy that can return both JSON and XML, but at a choice will default to XML. Here's my method:
@GET
@Path("/content")
@Produces({MediaType.APPLICATION_开发者_开发知识库XML, MediaType.APPLICATION_JSON})
public String contentListRequestXml(@Context HttpServletRequest req,
@Context HttpServletResponse response, @Context UriInfo info, @Context HttpHeaders h) {
response.setContentType(MediaType.APPLICATION_XML);
if(isXml)
return generateXML();
else
return generateJSON();
}
The problem that I have is that it is returning two Content-Types:
$ curl http://localhost:1234/content -i -H "Accept: application/json,application/xml" -I HTTP/1.1 200 OK
Content-Type: application/xml
Content-Type: application/json
Content-Length: 0
Server: Jetty(6.1.25)
How do I stop resteasy from setting the second Content-Type, or is there a better way to do this without having to have two separate functions on the same @Path but with different @Produces annotations?
The other option is to not bother with the response.setContentType and have @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) and let Resteasy deal with it, but how do I detect the matched mediatype that will be returned? I can get the HttpHeaders object and call getAcceptableMediaTypes() on it, but this means I have to effectively re-interpret the Accept Header that resteasy has already done for me. Surely there must be a way of getting the returned MediaType from resteasy when you supply multiple @Produces parameters?
Reading the @Produces section of this page http://wikis.sun.com/display/Jersey/Overview+of+JAX-RS+1.0+Features, it appears that the spec wants the app to choose whichever content type matches the HTTP Accept header. And if all of the content types in the @Produces
annotation match, it should just use the first one.
So I'm thinking one of two things. It's possible that Resteasy doesn't properly implement the spec. It's also possible that the @Produces
annotation and the .setContentType
call aren't playing nice. I'm not a JAX-RS master, but I thought that the Produces annotation was there so that you don't have to directly interact with Response
objects.
精彩评论