Read HTTP Request Header in Spring MVC

In this Spring MVC tutorial, you will learn how to read HTTP Request Header in the Rest Controller class of your Application. To read HTTP Request Header in Spring MVC application we use @RequestHeader annotation.

@RequestHeader(value="Accept") String acceptHeader

Reading HTTP Request Header

For example, let’s assume we need to create a method in our Rest Controller class that accepts HTTP Get Request with two headers and the returns these same headers back in a Response Body. To break it down in steps I will need to:

  • Accept HTTP GET Request,
  • Read an “Accept” HTTP Request Header,
  • Read an “Authorization” HTTP Request Header,
  • Return the values of both headers in HTTP Response body

Below is a working code snippet that does that:

@RestController
@RequestMapping("/users") // http://localhost:8080/users
public class UserController {

    @GetMapping(path = "/myrequestheaders", produces = {MediaType.APPLICATION_JSON_VALUE} )
    public ResponseEntity<Map<String, String>> getMyRequestHeaders(
            @RequestHeader(value="Accept") String acceptHeader,
            @RequestHeader(value="Authorization") String authorizationHeader
            )
    {
        Map<String, String> returnValue = new HashMap<>();
        returnValue.put("Accept", acceptHeader);
        returnValue.put("Authorization", authorizationHeader);
        
        return ResponseEntity.status(HttpStatus.OK).body(returnValue);
    }


}

Read All HTTP Headers

If you need to read all HTTP Request headers rather than a one specific header, then you can do it by reading an entire list of HTTP Request Headers from a HttpServletRequest object.

Import into your Rest Controller class the HttpServletRequest:

import javax.servlet.http.HttpServletRequest;

and then you can add the HttpServletRequest as a method argument and read an entire collection of HTTP Header names:

Enumeration<String> hearderNames = request.getHeaderNames();

Below is a little code snippet that reads HTTP Request Headers and returns back in a body of HTTP Response each Header name and the value it holds.

@GetMapping(path = "/myrequestheaders", produces = {MediaType.APPLICATION_JSON_VALUE} )
public ResponseEntity<Map<String, Object>> getMyRequestHeaders(HttpServletRequest request)
{
    Map<String, Object> returnValue = new HashMap<>();
 
    Enumeration<String> hearderNames = request.getHeaderNames();
    while(hearderNames.hasMoreElements())
    {
    	String headerName = hearderNames.nextElement();
    	returnValue.put(headerName, request.getHeader(headerName));
 }
   
    return ResponseEntity.status(HttpStatus.OK).body(returnValue);
}

Response:

{
    "authorization": "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ0ZXN0MUB0ZXN0LmNvbSIsImV4cCI6MTU0NDcxNDE5OX0.zsGpNZ-nSIPImwsN7ejS9Lo3EuDZ7qZCPz3w48ZNBw9tmecJNXlH7pXQLNG3OxJr4BQKTJuy4BdLy08RH0UBtQ",
    "postman-token": "cfeb1c41-24e2-4f43-b373-b12ccd4d0045",
    "host": "localhost:8080",
    "connection": "keep-alive",
    "cache-control": "no-cache",
    "accept-encoding": "gzip, deflate",
    "accept": "application/json",
    "user-agent": "PostmanRuntime/7.4.0"
}

 

 

I hope this short Spring MVC tutorial was helpful for you.

To learn more about Spring MVC and Spring Boot, check the below list of video courses: