当前位置: 代码网 > it编程>编程语言>Java > 如何在SpringBoot中使用@RequestBody注解正确接收非JSON格式的字符串参数?

如何在SpringBoot中使用@RequestBody注解正确接收非JSON格式的字符串参数?

2025年03月28日 Java 我要评论
spring boot中@requestbody注解接收非json字符串参数在spring boot应用中,@requestbody注解通常用于处理json格式的请求体数据。然而,当需要处理非json

如何在springboot中使用@requestbody注解正确接收非json格式的字符串参数?

spring boot中@requestbody注解接收非json字符串参数

在spring boot应用中,@requestbody注解通常用于处理json格式的请求体数据。然而,当需要处理非json格式的字符串参数时,需要一些额外的配置。本文将探讨如何使用@requestbody正确接收非json字符串参数,并解决可能出现的json解析错误。

问题描述

一个spring boot控制器接口使用@requestbody接收字符串参数:

@responsebody
@postmapping("/sendnews")
public string sendcontent(httpservletrequest request, @requestbody string lstmsgid) {
    system.out.println(lstmsgid);
    return lstmsgid;
}
登录后复制

使用postman发送请求(请求体设置为raw,内容为"90c8c36f23a94c1487851129aa47d690/90c8c36f23a94c1487851129aa47d690")可以正常工作。但使用hutool库发送相同请求时:

httprequest request = httprequest.post(url);
request.header("gatewayauth", "xxxx");
string responsejsonstr = request.form(null)
        .body("90c8c36f23a94c1487851129aa47d690/90c8c36f23a94c1487851129aa47d690")
        .timeout(50000)
        .execute().body();
登录后复制

则抛出org.springframework.http.converter.httpmessagenotreadableexception异常,提示json解析错误。

原因分析

postman默认将请求体字符串用双引号包围,符合json字符串格式。spring接收到后,使用json解析器处理。而hutool库的请求缺少必要的http头信息,导致spring误将请求体当作json处理,从而导致解析失败。

解决方法

为了让@requestbody正确处理非json字符串,需要明确告知spring请求体的类型。这可以通过设置content-type请求头为text/plain来实现。

修改hutool请求代码:

httprequest request = httprequest.post(url);
request.header("content-type", "text/plain");
request.header("gatewayauth", "xxxx");
string responsejsonstr = request.body("90c8c36f23a94c1487851129aa47d690/90c8c36f23a94c1487851129aa47d690")
        .timeout(50000)
        .execute().body();
登录后复制

通过设置content-type为text/plain,spring将正确解析请求体中的非json字符串参数。

以上就是如何在springboot中使用@requestbody注解正确接收非json格式的字符串参数?的详细内容,更多请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com