java - Spring Boot中获取请求头

标签 java spring request

如何从调用我的 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/

相关文章:

java - Thymeleaf - 异常评估 SpringEL 表达式

c# - java是否有类似于C#属性的东西?

Node.js 请求模块获取 ETIMEDOUT 和 ESOCKETTIMEDOUT

java - 使用滑动手势向上/向下移动对象

java - Spring Batch JobExecutionException - ConcurrencyFailureException

java - 客户端发送的请求语法不正确 - Spring mvc

java - Spring RestTemplate - 异步与同步 restTemplate

python - 如何在 python 中模拟 http.server 以实现更快的单元测试?

node.js - NPM Request - 如何返回请求的主体?

java - Spring : Request method 'POST' not supported