我正在使用 Resteasy 编写一个可以返回 JSON 和 XML 的应用程序,但可以选择默认为 XML。这是我的方法:
@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();
}
我遇到的问题是它返回两个内容类型:
$ 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)
我如何阻止 resteasy 设置第二个 Content-Type,或者有没有更好的方法来做到这一点,而不必在同一个 @Path 上有两个单独的函数但使用不同的 @Produces 注释?
另一种选择是不理会 response.setContentType 并使用 @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) 并让 Resteasy 处理它,但我如何检测将返回的匹配媒体类型?我可以获得 HttpHeaders 对象并对其调用 getAcceptableMediaTypes(),但这意味着我必须有效地重新解释 resteasy 已经为我完成的 Accept Header。当您提供多个@Produces 参数时,肯定有一种方法可以从 resteasy 获取返回的 MediaType 吗?
最佳答案
阅读本页的@Produces 部分 http://wikis.sun.com/display/Jersey/Overview+of+JAX-RS+1.0+Features , 规范似乎希望应用程序选择与 HTTP Accept header 匹配的内容类型。如果 @Produces
注释中的所有内容类型都匹配,它应该只使用第一个。
所以我在考虑两件事之一。 Resteasy 可能没有正确实现规范。也有可能 @Produces
注释和 .setContentType
调用效果不佳。我不是 JAX-RS 专家,但我认为 Produces 注释就在那里,这样您就不必直接与 Response
对象交互。
关于java - Resteasy Content-Type 默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6614400/