Getting Http Headers from Request(@HeaderParam,HttpHeaders) in JAX-RS

This tutorial shows how to extract header parameters from http request in JAX-RS.

Example Scenario :

We have to create a REST web service which returns some or all the header fields of an http request to the caller.


Project artifacts:

1. Technologies used –

a. Eclipse IDE for Java EE developer 4.5.0.20150621-1200 (Mars)
b. Preinstalled Maven with Eclipse Mars
c. Tomcat 7.0.64
d. RESTEasy 3.0.4.Final
e. Java 1.8
 

Jars used –

javax.ws.rs-api-2.0.jar
resteasy-jaxrs-3.0.4.Final.jar
jaxrs-api-3.0.4.Final.jar
slf4j-simple-1.5.8.jar
slf4j-api-1.5.8.jar
scannotation-1.0.3.jar
javassist-3.12.1.GA.jar
jboss-annotations-api_1.1_spec-1.0.1.Final.jar
activation-1.1.jar
httpclient-4.2.1.jar
httpcore-4.2.1.jar
commons-logging-1.1.1.jar
commons-codec-1.6.jar
commons-io-2.1.jar
jcip-annotations-1.0.jar
 

2. Eclipse project folder structure:

 

Header Param DirectoryStructure

3. Web Project

Create a standard web project in Eclipse by following the below link.

Create a Maven Web Project

4. Maven Dependencies

file:pom.xml. Maven unit of work to declare project dependencies, compile code and build war file for deployment in Tomcat.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.javanbeyond</groupId>
    <artifactId>WorkingWithHeaderParam</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>Restful Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>3.0.4.Final</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>WorkingWithHeaderParam</finalName>
    </build>
</project>

 

5. Application class

file: MyApplication.java. The Class that registers the resource class OrderReceiver with JAX-RS runtime. It has two sets.
Our resource class should be added to the singleton set.

 

package com.javanbeyond.service;

import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;

public class MyApplication extends Application {
    private Set<Object> singletons = new HashSet<Object>();
    private Set<Class<?>> empty = new HashSet<Class<?>>();

    public MyApplication() {
        singletons.add(new OrderReceiver());
    }

    @Override
    public Set<Class<?>> getClasses() {
        return empty;
    }

    @Override
    public Set<Object> getSingletons() {
        return singletons;
    }
}

 

6. Resource class

file: OrderReceiver.java . In JAX-RS, we use @HeaderParam annotation to extract specific header fields and HttpHeaders class to get all the header values in Resource methods.

Case 1 : Getting specific header values.

In the method getHeader, we inject two header fields with the help of @HeaderParam annotation. ‘customValue” header is set by us in our client code and “user-agent” is set by browser. It returns the extracted header field values to the client.

 

    // This method extracts two header values.
    // "customValue" is set up by us and "user-agent" is standard header
    // parameter set up by browser
    // @HeaderParam gets both these values and pass it to method parameters.
    @GET
    @Path("/header")
    public Response getHeader(@HeaderParam("customValue"String customValue,
            @HeaderParam("user-agent"String userAgent) {
        System.out.println("inside getHeader");
        return Response.status(200).entity(
                "customValue:" + customValue + "\nuser-agent:" + userAgent)
                .build();
    }

 

Case 2: Getting all header fields from http request

In the method getAllHeaders, we are using @Context annotation with class HttpHeaders to inject all the header fields to the method parameter. It returns all the header values to the client.

    // Get all the headers of the request injected by Context
    @GET
    @Path("/headers")
    public Response getAllHeaders(@Context HttpHeaders headers) {
        System.out.println("inside getAllHeaders");
        StringBuilder sb = new StringBuilder();
        for (String header : headers.getRequestHeaders().keySet()) {
            sb.append(header + ":" + headers.getRequestHeader(header"\n");
        }
        return Response.status(200).entity(sb.toString()).build();
    }

7. Deployment descriptor

file: web.xml . Deployment descriptor file for mapping URIs to servlet. Application class is registered by setting as init param to the servlet.

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    <display-name>Archetype Created Web Application</display-name>
    <context-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/rest</param-value>
    </context-param>
    <servlet>
        <servlet-name>rest</servlet-name>
        <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.javanbeyond.service.MyApplication</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>rest</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>client.html</welcome-file>
    </welcome-file-list>
</web-app>

 


Example Execution:

  1. Deploy the application in Tomcat and type the URI “http://localhost:8080/WorkingWithHeaderParam/” on your browser. You should get a client as below:

Header Param Client

2. Click on “getHeader” button to get our custom header which is set by us and the header “user-agent” which is set by browser.

 

JAX-RS HeaderParam

3. Click on “getAllHeaders” button to get all the header fields of Http request from client.

 

JAX-RS HttpHeaders

 

 

 

Back to Top