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

发布于 2024-09-18 09:30:41 字数 313 浏览 3 评论 0原文

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

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

如果请求定向到仅接受 text/* jersey 的 create 将返回 500。有没有办法解决此问题? (我无法更改请求接受标头)。

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?

@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).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不知在何时 2024-09-25 09:30:41

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

 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);

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

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

 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文