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



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

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

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

public String getResponse(@RequestBody SomeObject object,
 @RequestHeader("Content-type") String contentType) {

另一种方法是,这种HttpServletRequest注射将在春天得到照顾

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

  Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = (String) headerNames.nextElement();
        String value = request.getHeader(key);

定义所需的任何控制器方法签名,可能使用给定方案的参数注释之一(如@RequestParam、@RequestHeader、@PathVariable等(。

参考: 15. 网络MVC框架

最新更新