【问题标题】:Get request header in spring boot在 Spring Boot 中获取请求标头
【发布时间】:2020-05-23 00:25:23
【问题描述】:

如何从调用我的 Springboot 应用程序的应用程序中获取当前请求的标头和正文?我需要提取这些信息。不幸的是,这不起作用。我尝试使用此代码示例 (https://stackoverflow.com/a/26323545/5762515) 获取当前请求:

public static HttpServletRequest getCurrentHttpRequest(){
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes instanceof ServletRequestAttributes) {
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        return request;
    }
    throw new IllegalArgumentException("Request must not be null!");
}

然后我试图得到尸体

ContentCachingRequestWrapper requestWrapper = (ContentCachingRequestWrapper) currentRequest;
    String requestBody = new String(requestWrapper.getContentAsByteArray());

谁能告诉我我做错了什么? 提前致谢

【问题讨论】:

    标签: java spring request


    【解决方案1】:
    @RestController
    public class SampleController {
    
        @PostMapping("/RestEndpoint")
        public ResponseEntity<?> sampleEndpoint(@RequestHeader Map<String, String> headers,@RequestBody Map<String,String> body) {
            //Do something with header / body
            return null;
        }
    }
    

    如果应用程序通过休息端点进行通信,我相信这将是最简单的解决方案。在 spring 中,您可以将 RequestHeader 和 RequestBody 注释添加到方法参数以设置它们以供使用。

    当然,您可以将 RequestBody 直接映射到某个 POJO,而不是使用映射,但仅作为示例。

    如果这就是你要找的,请告诉我!

    【讨论】:

      【解决方案2】:

      @TryHard,您使用的是 spring boot,那么下面的方式更适合您,

      @RestController
      public class SampleController {
          @RequestMapping("/get-header-data")
          public ResponseEntity<?> sampleEndpoint(HttpServletRequest request) {
              // request object comes with various in-built methods use as per your requirement.
              request.getHeader("<key>");
          }
      }
      

      【讨论】:

        【解决方案3】:

        您可以在代码中获取标题,但需要进行一些更改。

        private String getRequest() throws Exception {
                RequestAttributes attribs = RequestContextHolder.getRequestAttributes();
                if (attribs != null) {
                    HttpServletRequest request = ((ServletRequestAttributes) attribs).getRequest();
                    return request ;
                }
                
                throw new IllegalArgumentException("Request must not be null!");
        }
        

        在您可以从请求中提取标头信息之后。例如,如果您想获取 Accept-Encoding

        String headerEncoding = getRequest().getHeader("Accept-Encoding");
        

        如果没有必要,你不会使用这个方法。

        如果您想提取身体,请不要使用此解决方案

        【讨论】:

          猜你喜欢
          • 2019-12-26
          • 2022-11-30
          • 2016-11-03
          • 1970-01-01
          • 2023-03-23
          • 2018-12-18
          • 2019-03-21
          • 2020-12-09
          • 2020-12-29
          相关资源
          最近更新 更多