1. Overview

This article is about Spring MVC read HTTP Request header in Spring boot Rest Service or Spring MVC Controller. @RequestHeader is a annotation using that we can read individual healer or all request headers information with name and value inside the Controller or RestController. We have also explained about to read header information using our traditional ways HttpServletRequest.

2. Different ways to Read HTTP Request header / @RequestHeader Examples

2.1 Spring MVC read header using @RequestHeader

@RequestHeader is a Spring MVC web annotation using that we can read HTTP header information. it requires header name as a parameter, Here is an example for same:

@RestController
public class EmployeeController {

    @RequestMapping("/getEmployees")
    public List<Employee> getEmployees(@RequestHeader(HttpHeaders.ACCEPT)String accept, 
                                   @RequestHeader(HttpHeaders.USER_AGENT)String userAgent) {

       System.out.println(accept);    // it will print 'Accept' header
       System.out.println(userAgent);  // it will print 'User-Agent' header

        return Employee.getEmployee();
 }
}

Output:

http://localhost:8282/getEmployees

text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36

2.2 Spring MVC read all headers

@RequestHeader annotation without any parameter will return all the header information. Here is an example for the same:

@RestController
public class EmployeeController {

@RequestMapping("/getEmployees")
   public List<Employee> getEmployees(@RequestHeader HttpHeaders httpHeaders) {
       httpHeaders.forEach((headerName, HeaderValue) -> {
           System.out.println("Header Name:"+headerName + ", Header Value:"+HeaderValue);
       });
       return Employee.getEmployee();
   }
}

Output:

http://localhost:8282/getEmployees

Header Name:host, Header Value:[localhost:8282]
Header Name:connection, Header Value:[keep-alive]
Header Name:cache-control, Header Value:[max-age=0]
Header Name:upgrade-insecure-requests, Header Value:[1]
Header Name:user-agent, Header Value:[Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 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]
Header Name:accept-encoding, Header Value:[gzip, deflate, br]
Header Name:accept-language, Header Value:[en-US,en;q=0.9]

2.3 Spring MVC read the custom header

@RequestHeader requires any header whether it should predefine header names or custom header name. @RequestHeader also allowed defaultValue so if the header is not available in the request then it will take a default value. required where true means header is compulsory in request otherwise  Spring will not accept the request, false means header is Optional.

@RestController
public class EmployeeController {

@RequestMapping("/getEmployees")
   public List<Employee> getEmployees(@RequestHeader(value = "My-Custom-Header", required = true)String myCustomHeader,
                                      @RequestHeader(HttpHeaders.USER_AGENT)String userAgent) {
       System.out.println(myCustomHeader);
       System.out.println(userAgent);
       return Employee.getEmployee();
   }
}

If My-Custom-Header header is not available in the request then it will throw an exception like:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun Sep 09 12:37:51 IST 2018
There was an unexpected error (type=Bad Request, status=400).
Missing request header 'My-Custom-Header' for method parameter of type String

http://localhost:8282/getEmployees using POSTMan tool with custom headers:

Spring MVC custom header

Spring MVC custom header

Output:

Java Developer Zone
Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36

2.4 Read Header Using HttpServletRequest

HttpServletRequest is class which contains all the information about request including headers.

  • HttpServletRequest.getHeader(HEADER_NAME) is method requires header name as parameter and return header value as String.
  • HttpServletRequest.getHeaderNames() will return names of all the header which are available in request. It will return Enumeration which contains all header name and once we have header name then we can get header value using HttpServletRequest.getHeader() method.
@RestController
public class EmployeeController {
  
   @RequestMapping("/getEmployees")
   public List<Employee> getEmployees(HttpServletRequest httpRequest) {
       System.out.println(httpRequest.getHeader("Accept"));        // fetch single header

       Enumeration<String> enumeration = httpRequest.getHeaderNames();   // fetch header names
       while (enumeration.hasMoreElements()){                     // print all headers
           String headerName = enumeration.nextElement();
           System.out.println("Header Name:"+headerName + ", Header Value:"+ httpRequest.getHeader(headerName));
       }

       return Employee.getEmployee();
   }
}

3. Conclusion

In this article, we learned different ways to read the header information using @RequestHeader annotation and it’s part of spring web so in spring boot application if spring boot web dependency is included then we can use in spring boot application also. And we learn that how spring web make our code easy using annotations.

4. References

 

 

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No

Leave a Reply

Your email address will not be published. Required fields are marked *