JAXRS CXF - 获取http标头而不指定方法参数

Kon*_*rad 3 java rest cxf jax-rs http-headers

是否可以在JAXRS资源方法中检索http标头而无需将这些标头明确指定为方法参数?

例如,我有一个以下界面:

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

  @GET
  public List<Post> getAllPosts();
}
Run Code Online (Sandbox Code Playgroud)

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

public class PostsResourceImpl implements PostsResource {

  @Autowired
  private PostsService postsService;

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

}
Run Code Online (Sandbox Code Playgroud)

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

public List<Post> getAllPosts(@HeaderParam("X-MyCustomHeader") String myCustomHeader);
Run Code Online (Sandbox Code Playgroud)

此标头将由客户端上的拦截器添加,因此客户端代码不知道放在此处的内容,这不应该是显式方法参数.

Thi*_*ier 6

您可以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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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