JAX-RS - Injecting HttpHeaders with @Context annotation

[Updated: Sep 10, 2017, Created: Sep 10, 2017]

An instance of HttpHeaders can be injected as field or method parameter using the @Context annotation. HttpHeaders provides access to HTTP request header information.

Example

A JAX-RS resource injecting HttpHeaders

@Path("/users")
public class UserResource {
  @Context
  private HttpHeaders httpHeaders;

  @GET
  public String getUsers() {
      System.out.println("In getUsers() method");
      printHeaderInfo();
      return "returning dummy user list";
  }

  private void printHeaderInfo() {
      System.out.println("---------------");
      MultivaluedMap<String, String> requestHeaders = httpHeaders.getRequestHeaders();
      for (Map.Entry<String, List<String>> entry : requestHeaders.entrySet()) {
          System.out.println(entry.getKey() + "=" + entry.getValue());
      }
  }
}

The client

public class UserClient {
  public static void main(String[] args) throws Exception {
      Client client = ClientBuilder.newBuilder().build();
      WebTarget target =
              client.target("http://localhost:8080/users");

      String response = target.request()
                              .header("aCustomHeader", "aValue")
                              .get(String.class);
      System.out.println("response: " + response);
  }
}

Output

response: returning dummy user list

Output on server console

In getUsers() method
---------------
acustomheader=[aValue]
user-agent=[Jersey/2.25.1 (HttpUrlConnection 1.8.0_111)]
host=[localhost:8080]
accept=[text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2]
connection=[keep-alive]

Example Project

Dependencies and Technologies Used :

  • jersey-server 2.25.1: Jersey core server implementation.
  • jersey-container-servlet 2.25.1: Jersey core Servlet 3.x implementation.
  • JDK 1.8
  • Maven 3.3.9

@Context HttpHeaders Example Select All Download
  • injecting-http-headers
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also