How to read HTTP Headers in a Spring Controller

In this Spring tutorial, we will look at how to read HTTP Headers in a Spring Controller. We will look at the options to access HTTP headers in a Spring Rest Controller. We will closely look at the @RequestHeaderannotation. When we annotate a parameter with @RequestHeader, the parameter retrieves the header information.

 

1. Maven Setup

We will use Spring Boot for this post, but the concept and setup is identical for simple Spring MVC application. Let’s add the web starter for our application. This is how our pom.xml looks like:

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.spring framework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/>
        <!-- lookup parent from repository -->
    </parent>
    <groupId>com.javadevjournal</groupId>
    <artifactId>http-header-spring</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>http-header-spring</name>
    <description>How to Read HTTP Headers in Spring REST Controllers</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

 

2. Read HTTP Headers

Let’s see how to read HTTP Headers in a Spring Controller. We will look at the following 2 options to access the header information:

  1. Read individual HTTP headers.
  2. Real all HTTP headers

 

2.1 Read individual HTTP Headers

To read individual HTTP header in Spring, we can use the @RequestHeader annotation and specify the header name as the parameter. Let’s take an example where we want to read the "accept-language" header information in our controller.

@RestController
public class SessionDemoController {

    private static final Logger LOG = LoggerFactory.getLogger(SessionDemoController.class);

    @GetMapping("/get-session-count")
    public String testSessionListner(HttpServletRequest request, HttpServletResponse response){

        HttpSession session = request.getSession(false);
        if(session == null){
            LOG.info("Unable to find session. Creating a new session");
            session = request.getSession(true);
        }
        return "Session Test completed";
    }
}

 

2.2 Read All HTTP Headers

To read all http header in your Spring Boot application, we use the same @RequestHeader annotation. To collect all the header values, we have the option to collect values in to Map, a MultiValueMap or a HttpHeaders object. Let’s see how to do this: 

@RestController
public class AllHeaderController {

    @GetMapping("/print-all-headers")
    public void getAllheaders(@RequestHeader Map<String,String> headers){
        headers.forEach((key,value) ->{
            System.out.println("Header Name: "+key+" Header Value: "+value);
        });
    }
}

If we run our application and open the following URL http://host:port/print-all-headers, you may see a similar output in the console:

Header Name: host Header Value: localhost:8080
Header Name: connection Header Value: keep-alive
Header Name: upgrade-insecure-requests Header Value: 1
Header Name: user-agent Header Value: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36
Header Name: accept Header Value: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Header Name: accept-encoding Header Value: gzip, deflate, br
Header Name: accept-language Header Value: en-US,en;q=0.9
Header Name: cookie Header Value: JSESSIONID=14668EF3CA04AAB9156757F5BADB00D9

 

3.  Summary

In this post, we saw how to read HTTP Headers in a Spring Controller. We saw how to read individual as well all the http headers in our Spring Boot application. As always, the source code for this article is available on the GitHub.