Retrieving header parameters in JAX-RS annotated method

The post explains different ways of retrieving header parameters in JAX-RS annotated method.

Below is the complete code

1  package resource;
3  import;
4  import;
5  import;
6  import;
7  import;
8  import;
9  import;
11 @Path("webresource3")
12 public class WebResource3 {
13  @GET
14  @Path("headerParameters1")
15  public Response getHeaderParameters1(@HeaderParam("param1") String param1) {
16      Response response = Response.ok(param1, MediaType.TEXT_PLAIN).build();
17      return response;
18  }
20  @GET
21  @Path("headerParameters2")
22  public Response getHeaderParameters2(@Context HttpHeaders headers) {
23      String value = headers.getRequestHeader("param1").get(0);
24      Response response = Response.ok(value, MediaType.TEXT_PLAIN).build();
25      return response;
26  }
27 }

The above web resource can be accessed using the below two urls

In the first method getHeaderParameters1, the variable param1 is annotated by HeaderParam. This to inform to the JAX-RS runtime that the value has to be taken from the request header using header name passed to the HeaderParam annotation (i.e., in this param1) and inject the value to the variable param1.

In the second method getHeaderParameters2, we use the Context annotation. This annotation is used to inject context information, in this case HttpHeaders instance. HttpHeaders instance provides request header information. Once you get the HttpHeaders instance, we can get the param1 header information as shown in
the above code at line 23.

Leave a Reply