如何在 Spring REST 服务中获取所有传入请求的详细信息?

cat*_*hyk 1 java spring http-post spring-boot

我想查看使用 Spring Boot 构建的端点中的所有请求相关详细信息(例如标头、正文)。如何获得?

@RestController
public class SomeRestController {
    ...
    @PostMapping("path/")
    public String getResponse(@RequestBody SomeObject object) {
        // There I want to look at Request details... but how?
        ...
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

Dea*_*ool 5

如果你想得到RequestHeader你可以简单地在方法中使用@RequestHeader注释

public String getResponse(@RequestBody SomeObject object,
 @RequestHeader("Content-type") String contentType) {
Run Code Online (Sandbox Code Playgroud)

另一种方法是,这种注入HttpServletRequest将由 spring 负责

 public String getResponse(HttpServletRequest request, 
  @RequestBody SomeObject object) {
String userAgent = request.getHeader("content-Type");
}
Run Code Online (Sandbox Code Playgroud)

或者

  Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = (String) headerNames.nextElement();
        String value = request.getHeader(key);
Run Code Online (Sandbox Code Playgroud)