【问题标题】:How to get all incoming request details in Spring REST service?如何在 Spring REST 服务中获取所有传入请求的详细信息?
【发布时间】:2018-08-08 19:34:58
【问题描述】:

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

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

【问题讨论】:

  • 只需将HttpServletRequest 添加为参数,然后随心所欲地使用它。

标签: java spring spring-boot http-post


【解决方案1】:

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

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

另一种方法是,HttpServletRequest 的注入将由 spring 处理

 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);

【讨论】:

  • 表头有非标部分怎么办?那么,如果我想查看整个标题部分怎么办?
  • 第三个我们得到完整的标题和值
【解决方案2】:

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

参考: 15. Web MVC framework

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2016-12-07
    • 2022-11-18
    • 2018-04-29
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    相关资源
    最近更新 更多