How to get HTTP header information in Spring REST Controller


In this article, we will explore how to access HTTP header information in Spring Rest Controller.
First, we will use the @ RequestHeader annotation to read the HTTP header information separately or simultaneously.
After that, we will delve into the properties of @ RequestHeader.

Get HTTP header information

Get single HTTP header information

If we need to access a specific HTTP header, we can configure @ RequestHeader with the header name:

public ResponseEntity<String> greeting(@RequestHeader("accept-language") String language) {
    // Code using the language variable
    return new ResponseEntity<String>(greeting, HttpStatus.OK);

We can then access the value using the variable passed to our method If the header information named accept language is not found in the request, the method returns a "400 Bad Request" error.
Our header information is not necessarily a string. For example, if we know our header is a number, we can declare our variable as a number type:

public ResponseEntity<String> doubleNumber(@RequestHeader("my-number") int myNumber) {
    return new ResponseEntity<String>(String.format("%d * 2 = %d", 
      myNumber, (myNumber * 2)), HttpStatus.OK);

Get multiple HTTP headers

If we're not sure which headers will appear, or if we need more than we need in the method signature, we can use the @ RequestHeader annotation instead of a specific name.
For variable types, we have several choices: Map, MultiValueMap, or HttpHeaders objects.
First, let's get the header information of the request in the form of Map:

public ResponseEntity<String> listAllHeaders(@RequestHeader Map<String, String> headers) {
    headers.forEach((key, value) -> {"Header '%s' = %s", key, value));
    return new ResponseEntity<String>(
      String.format("Listed %d headers", headers.size()), HttpStatus.OK);

If we use Map, and one of the header information has multiple values, we can only get the first value. This is equivalent to using the getFirst() method on a MultiValueMap.
If our header information may have multiple values, we can get them as MultiValueMap:

public ResponseEntity<String> multiValue(@RequestHeader MultiValueMap<String, String> headers) {
    headers.forEach((key, value) -> {
          "Header '%s' = %s", key,"|"))));
    return new ResponseEntity<String>(
      String.format("Listed %d headers", headers.size()), HttpStatus.OK);

We can also get headers as HttpHeaders object:

public ResponseEntity<String> getBaseUrl(@RequestHeader HttpHeaders headers) {
    InetSocketAddress host = headers.getHost();
    String url = "http://" + host.getHostName() + ":" + host.getPort();
    return new ResponseEntity<String>(String.format("Base URL = %s", url), HttpStatus.OK);

When we access header information by name from a Map, MultiValueMap, or HttpHeaders object, if it does not exist, it returns null.

@RequestHeader property

Now that we know the basics of using the @ RequestHeader annotation to get the request header, let's take a closer look at its properties.
When we specify the Header, we have implicitly used the name or value attribute:

public ResponseEntity<String> greeting(
  @RequestHeader("accept-language") String language) {}

We can do the same thing by using the name attribute:

public ResponseEntity<String> greeting(
  @RequestHeader(name = "accept-language") String language) {}

Next, let's use the value attribute in exactly the same way:

public ResponseEntity<String> greeting(
  @RequestHeader(value = "accept-language") String language) {}

When we specify to get a header, it is required by default If the header information is not found in the request, the controller returns a 400 error.
We can use the required attribute to indicate that our header is not required:

public ResponseEntity<String> evaluateNonRequiredHeader(
  @RequestHeader(value = "optional-header", required = false) String optionalHeader) {
    return new ResponseEntity<String>(String.format(
      "Was the optional header present? %s!",
        (optionalHeader == null ? "No" : "Yes")),HttpStatus.OK);

If the header information does not exist in the request header, the variable will be null, so make sure the program can run normally, and we will check the appropriate null value.
Let's use the defaultValue property to provide a default value for the header information:

public ResponseEntity<String> evaluateDefaultHeaderValue(
  @RequestHeader(value = "optional-header", defaultValue = "3600") int optionalHeader) {
    return new ResponseEntity<String>(
      String.format("Optional Header is %d", optionalHeader), HttpStatus.OK);

Concluding remarks

In this short tutorial, we learned how to access request headers in Spring REST Controllers. First, we use the @ RequestHeader annotation to get the request header for the Controller method.
After knowing the basic knowledge, we studied the properties of @ RequestHeader annotation in detail.

Welcome to my public address: Qu Ling Feng, get exclusive exclusive learning resources and daily dry goods push.
If you are interested in my topic content, you can also follow my blog:

Tags: Programming Attribute Spring REST

Posted on Wed, 06 Nov 2019 20:04:58 -0500 by tgh