Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXRS CXF - get http headers without specifying as method parameters

Is it possible to retrieve http headers inside JAXRS resource method without explicitly specifying these headers as method parameters?

For example I have a following interface:

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

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

and the following class that implements this interface:

public class PostsResourceImpl implements PostsResource {

  @Autowired
  private PostsService postsService;

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

}

I don't want to change my method signature to:

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

This header will be added by interceptor on the client side so the client code doesn't know what to put here and this should not be explicit method parameter.

like image 410
Konrad Avatar asked Mar 17 '15 15:03

Konrad


1 Answers

You can inject an object of type HttpHeaders within your resource as class variable to have access to request headers, as described below:

@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();
    }
}

Hope it answers your question. Thierry

like image 115
Thierry Templier Avatar answered Sep 30 '22 16:09

Thierry Templier