【问题标题】:JAXRS CXF - get http headers without specifying as method parametersJAXRS CXF - 获取 http 标头而不指定为方法参数
【发布时间】:2015-03-17 15:12:35
【问题描述】:

是否可以在 JAXRS 资源方法中检索 http 头而不将这些头显式指定为方法参数?

例如我有如下界面:

@Path("/posts")
public interface PostsResource {

  @GET
  public List<Post> getAllPosts();
}

以及实现此接口的以下类:

public class PostsResourceImpl implements PostsResource {

  @Autowired
  private PostsService postsService;

  public List<Post> getAllPosts() {
    return postsService.getAllPosts();
  }

}

我不想将我的方法签名更改为:

public List<Post> getAllPosts(@HeaderParam("X-MyCustomHeader") String myCustomHeader);

此标头将由客户端的拦截器添加,因此客户端代码不知道该放什么,这不应该是显式的方法参数。

【问题讨论】:

    标签: java rest http-headers cxf jax-rs


    【解决方案1】:

    您可以在资源中注入HttpHeaders 类型的对象作为类变量来访问请求标头,如下所述:

    @Path("/test")
    public class TestService {
        @Context
        private HttpHeaders headers;
    
        @GET
        @Path("/{pathParameter}")
        public Response testMethod() {
            (...)
            List<String> customHeaderValues = headers.getRequestHeader("X-MyCustomHeader");
            System.out.println(">> X-MyCustomHeader = " + customHeaderValues);
            (...)
    
            String response = (...)
            return Response.status(200).entity(response).build();
        }
    }
    

    希望它能回答你的问题。 蒂埃里

    【讨论】:

    • 效果很好。即使使用 @javax.ws.rs.HeaderParam("X-MyCustomHeader") 注释。谢谢你的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    相关资源
    最近更新 更多