@RestController – Reading HTTP Request fields (@RequestHeader)
Accessing the fields the HTTP client has set in the HTTP Request headers. It includes several information, such as COOKIES, accept-language, method, user-agent, etc.
When
developing endpoints using @RestController it is very simple to read http
request fields. Basically you have to map attributes of method annotated with
@RestController using the parameter annotation @RequestHeader("accept-language") String language. This annotation will
map the header field to the respective parameter variable, and when the method
is triggered by a HTTP Request, the parameter variable will already be filled
with the respective header field value.
You may see an example of the
code here:
@RequestMapping("/actors")
ResponseEntity
list(@RequestHeader("accept-language") String language) {
System.out.println("language:"+language);
return ResponseEntity(HttpStatus.OK);
}
It
is important to observe that when the header field is not available, an http error
is returned to the http client and the method is not executed.
You may download the source code here:
https://github.com/rafaelqg/code/blob/main/springboot_RequestHeader.java
Comments
Post a Comment