是否可以在 JAXRS 资源方法中检索 http header 而无需将这些 header 显式指定为方法参数?
例如我有一个如下界面:
@Path("/posts")
public interface PostsResource {
@GET
public List<Post> getAllPosts();
}
和下面实现这个接口(interface)的类:
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);
此 header 将由客户端的拦截器添加,因此客户端代码不知道将什么放在这里,这不应该是显式方法参数。
最佳答案
您可以在资源中注入(inject)类型为 HttpHeaders
的对象作为类变量,以访问请求 header ,如下所述:
@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();
}
}
希望它能回答您的问题。 蒂埃里
关于java - JAXRS CXF - 获取 http header 而不指定为方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29102757/