当前位置: 首页 > 图灵资讯 > 技术篇> 如何让SpringBoot中的@RequestBody注解正确接收非JSON格式的字符串参数?

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

来源:图灵教育
时间:2025-04-08 13:59:38

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

Spring 在boot应用中,正确接收请求参数非常重要,尤其是非JSON格式的字符串参数。本文将讨论如何使用@Requestbody注释正确接收此类参数。

我们遇到了Spring 使用@RequestBody注释Booot接收字符串参数的Boot接口:

@ResponseBody
@PostMapping(value = "/sendnews")
public String sendContent(HttpServletRequest request, @RequestBody String lstMsgId) {
    System.out.println(lstMsgId);
    return lstMsgId;
}

请求参数为:“90c8c36f23a94c148785129a47d690/90c8c36f23a94c148785129a47d690”。Postman直接发送参数可以正常工作,但使用Hutol工具发送时出现以下错误:

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: ...; nested exception is com.alibaba.fastjson.JSONException: ...

问题的根源在于Spring boot默认使用application/json处理@requestbody参数。当参数被双引号包裹时,Spring Boot将其视为JSON格式。 因此,对于非JSON字符串参数,我们需要显式指定要求的Contentent-Type。

解决方法是将要求的Content-Type设置为text//plain。这样,Spring Boot不会试图将其分析为JSON。

用Hutol工具类修改的代码如下:

HttpRequest request = HttpRequest.post(url);
request.header("Content-Type", "text/plain");
request.body("90c8c36f23a94c14875129a47d690/90c8c36f23a94c14875129a47d69");
String responseJsonStr = request.execute().body();

通过设置Contententtententent-Type: text/plain,@Requestbody注释可以正确接收非JSON格式的字符串参数。 这避免了不必要的JSON分析错误,保证了界面的稳定性和可靠性。

以上是如何让Springboot中的@requestbody注释正确接收非JSON格式的字符串参数?详情请关注图灵教育的其他相关文章!