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格式的字符串参数?的详细内容,更多请关注代码网其它相关文章!
发表评论