1. Introduction

In this short tutorial, we'll show how to read HTTP headers in Spring REST Controller by showing you how to use @RequestHeader annotation. We'll see how to extract both single and multiple headers using this annotation.

2. Read HTTP Headers in Spring REST Controller

For reading HTTP headers from Spring REST controller we'll be using @RequestHeader annotation. Let's see how to do this:

@GetMapping("/helloworld")
public String helloworld(@RequestHeader("headerAttribute") String headerAttribute) {
return headerAttribute;
}

If we want to read all headers at once, we can use the following approach:

@GetMapping("/helloworld")
public void helloworld(@RequestHeader Map<String, String> allAvailableHeaders) {
allAvailableHeaders.forEach((key, value) -> {
LOG.info(String.format("Header key and value: '%s' = %s", key, value));
});
}


As we can see, we're reading headers as a Map, where we can get specific headers by key name.


3. Conclusion

In this tutorial, we demonstrated how to extract HTTP headers from Spring REST Controller. We used @RequestHeader annotation to read both single and multiple HTTP headers.