Spring Cloud Gateway获取body

本文介绍了在Spring Cloud Gateway中如何正确获取和处理JSON格式的请求body,详细讲述了作者在不同版本Spring Boot和Spring Cloud Gateway中遇到的问题及解决过程,包括获取body不完整的情况和解决方案。文中提供了一个通过exchange.getAttribute('cachedRequestBodyObject')来获取body数据的示例,并展示了对于application/x-www-form-urlencoded和application/json两种类型请求的处理方式。
摘要由CSDN通过智能技术生成

前言

当前业务需求: 客户端传送数据的content_type: application/json, post请求,服务器需要从客request的中取出body进行网关的验权,然后把处理之后的数据重新封装到body中,经历查找问题解决问题的各种坑之后,痛定思痛,以此博客,希望能帮到有需求的人

获取body成功的 版本结合如下(其他的版本不保证适合本博客):
springboot 2.0.6.RELEASE + springcloud Finchley.SR2 + spring cloud gateway
maven依赖:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
 <!-- spring cloud 依赖-->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

采坑历史

一开始我使用的版本是:springboot 2.0.3.RELEASE + springcloud Finchley.RELEASE + spring cloud gateway, 尝试了网上铺天盖地的写法来获取body,最终失败,不是批判,只是觉得在技术上对于存在问题的应该要自己去亲自验证,并且秉着尊重技术的原则,不转载传播错误的博客。
如下获取body有异常的方法,该方法获取的body体不完整,在 查错过程章节里面也会特别说明现象和问题。

	/**
     * spring cloud gateway 获取post请求的body体
     * @param serverHttpRequest
     * @return
     */
    private String resolveBodyFromRequest(ServerHttpRequest serve
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值