Resteasy Content-Type 默认值
•浏览 1
Resteasy Content-Type defaults
我正在使用 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)
我遇到的问题是它返回了两个 Content-Type:
@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 吗?
阅读此页面 http://wikis.sun.com/display/Jersey/JAX-RS 1.0 功能概述的 @Produces 部分,规范似乎希望应用程序选择与 HTTP 接受匹配的任何内容类型标题。如果 @Produces 注释中的所有内容类型都匹配,它应该只使用第一个。
所以我在想两件事之一。 Resteasy 可能没有正确实施规范。 @Produces 注释和 .setContentType 调用也有可能表现不佳。我不是 JAX-RS 大师,但我认为 Produces 注释在那里,因此您不必直接与 Response 对象交互。