Read HTTP Request Header in Spring Boot REST

In this tutorial, you will learn how to read HTTP Request Header in the Rest Controller class of your Spring Boot application.

To read HTTP Request Header in Spring Boot REST application, we use @RequestHeader annotation.

@RequestHeader(value="Accept") String acceptHeader

To learn how to test if HTTP Header is received, read the tutorial about Testing HTTP Header value with REST Assured.

Reading HTTP Request Header

Let’s assume we need to create a method in our Rest Controller class that accepts HTTP Get Request with two headers and returns these same headers back in a Response Body. To break it down in steps, we 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 the HTTP Response body.

Below is a working code snippet that does that.

Code Example

@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 one specific header, you can do it by reading an entire list of HTTP Request Headers from a HttpServletRequest object.

Step 1

Import into your Rest Controller class the HttpServletRequest:

import javax.servlet.http.HttpServletRequest;

Step 2

Add the HttpServletRequest as a method argument and read an entire collection of HTTP Header names.

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

Code example

Below is a little code snippet that reads HTTP Request Headers and returns each header name in the HTTP Response body and its value.

@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"
}

Video Tutorial

https://youtu.be/DaCfA1IR29Q

 

I hope this Spring Boot tutorial was helpful for you. There are many other useful tutorials if you check the Spring Boot tutorials page.

However, if you like learning from a complete step-by-step video course, then below is a list of a few interesting courses:


Leave a Reply

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