gpt4 book ai didi

java - Spring Boot中获取请求头

转载 作者:行者123 更新时间:2023-11-30 01:40:47 26 4
gpt4 key购买 nike

如何从调用我的 Springboot 应用程序的应用程序获取当前请求的 header 和正文?我需要提取这些信息。不幸的是这不起作用。我尝试使用此代码示例获取当前请求(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());

有人可以告诉我我做错了什么吗?提前致谢

最佳答案

@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,而不是使用映射,但这只是一个示例。

请告诉我这是否是您正在寻找的内容!

关于java - Spring Boot中获取请求头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60103748/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com