在春季启动中获取请求标头

时间:2020-02-06 21:25:04

标签: java spring request

如何从名为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());

有人可以告诉我我做错了什么吗? 预先感谢

2 个答案:

答案 0 :(得分: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;
    }
}

如果应用程序正在通过其余端点进行通信,我相信这将是最简单的解决方案。在春季,您可以在方法参数中添加RequestHeader和RequestBody批注,以设置它们的使用方式。

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

让我知道这是否是您想要的!

答案 1 :(得分:1)

@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>");
    }
}