Linux JAX-RS Jersey - 如何强制响应 ContentType?覆盖内容协商

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3677064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:11:05  来源:igfitidea点击:

JAX-RS Jersey - Howto force a Response ContentType? Overwrite content negotiation

jerseyjax-rs

提问by Joe

Jersey identifies requests by looking at the accept header. I have a request which accepts only text/* - How can i force the response to be for example application/json?

Jersey 通过查看接受标头来识别请求。我有一个只接受 text/* 的请求 - 我如何强制响应为例如 application/json?

@POST
@Path("/create")
@Produces(MediaType.APPLICATION_JSON)
public MyResponseObject create() {
    return new MyResponseObject();
}

If a request is directed to create which only accepts text/* jersey will return a 500. Is there a way to workaround this issue? (I can't change the requests accept header).

如果请求创建只接受 text/* jersey 将返回 500。有没有办法解决这个问题?(我无法更改请求接受标头)。

回答by Arul Dhesiaseelan

Jersey also supports this via ResourceConfigproperty PROPERTY_MEDIA_TYPE_MAPPINGS that you could configure in your web.xml or programatically via Jersey APIs as shown below:

Jersey 还通过ResourceConfig属性 PROPERTY_MEDIA_TYPE_MAPPINGS支持此功能,您可以在 web.xml 中或通过 Jersey API 以编程方式进行配置,如下所示:

 DefaultResourceConfig rc = new DefaultResourceConfig(MyResource.class);
 rc.getMediaTypeMappings().put("json", MediaType.APPLICATION_JSON_TYPE);
 rc.getMediaTypeMappings().put("xml", MediaType.APPLICATION_XML_TYPE);
 SimpleServerFactory.create("http://localhost:9090", rc);

You can force content type negotiation by suffixing either .json or .xml to your URL.

您可以通过在 URL 后缀 .json 或 .xml 来强制内容类型协商。