How to set Accept header on the server side in Jersey 1.x for an incoming request

随声附和 提交于 2019-12-11 20:22:50

问题


I would like to know if there is a way to set the "Accept" headers for an incoming request on server side.

This is possible to do in Jersey 2.x by implementing and registering a @prematching ContainerRequestFilter but I have not found a way to achieve the same in Jersey 1.x versions.

The idea is to set an "Accept" header that is understood by '@Produces' annotation on a resource method. I am trying to handle a use case where the client cannot set an "Accept" header. So he specifies the kind of response he expects as a query parameter such as "type=json". The idea is to read the supplied type query parameter preferably in a filter and update the "Accept" header before the resource method with the '@Produces' annotation is called.

Please let me know if there is a way to achieve this.

Best regards,


回答1:


I think the preferred way to do this is with url extensions.

http://example.org/resource.xml

would return XML.

http://example.org/resource.json

would return JSON.

This can be implemented with a custom PackagesResourceConfig telling Jersey how to map extensions to media types:

public class ExampleResourceConfig extends PackagesResourceConfig {

  public ExampleResourceConfig(Map<String, Object> props) {
    super(props);
  }

  public ExampleResourceConfig(String... packages) {
    super(packages);
  }

  @Override
  public Map<String, MediaType> getMediaTypeMappings() {
    Map<String, MediaType> map = newHashMap();
    map.put("xml", MediaType.APPLICATION_XML_TYPE);
    map.put("json", MediaType.APPLICATION_JSON_TYPE);
    return map;
  }

}

If you're using a web.xml to configure Jersey you can set the javax.ws.rs.Application property to your PackagesResourceConfig class name.



来源:https://stackoverflow.com/questions/20212405/how-to-set-accept-header-on-the-server-side-in-jersey-1-x-for-an-incoming-reques

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!