在本教程中,您将学习如何读取 Spring Boot 应用程序的 Rest Controller 类中的 HTTP 请求标头。
要在 Spring Boot REST 应用程序中读取 HTTP 请求标头,我们使用@RequestHeader注释。
@RequestHeader(value="Accept") String acceptHeader
读取 HTTP 请求头
假设我们需要在 Rest Controller 类中创建一个方法,接受带有两个头信息的 HTTP Get 请求,并在响应体中返回相同的头信息。分步骤来说,我们需要
- 接受 HTTP GET 请求、
- 读取 "接受 "HTTP 请求头、
- 读取 "授权 "HTTP 请求头、
- 在 HTTP 响应体中返回这两个标头的值。
@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); }
}
|
读取所有 HTTP 标头
如果需要读取所有 HTTP 请求标头,而不是某个特定标头,可以从 HttpServletRequest 对象中读取整个 HTTP 请求标头列表。
步骤 1
将 HttpServletRequest 导入 Rest Controller 类:
import javax.servlet.http.HttpServletRequest;
步骤 2
将 HttpServletRequest 添加为方法参数,并读取整个 HTTP 头名称集合。
Enumeration<String> hearderNames = request.getHeaderNames();
代码示例
下面是一个小代码片段,用于读取 HTTP 请求头,并返回 HTTP 响应正文中的每个头名称及其值。
@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); }
|
响应:
{ "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" }
|