在Spring Boot应用中,正确接收请求参数至关重要,尤其是非JSON格式的字符串参数。本文将探讨如何使用@RequestBody注解正确接收这类参数。
我们遇到一个Spring Boot接口,使用@RequestBody注解接收字符串参数:
@ResponseBody @PostMapping(value = "/sendnews") public String sendContent(HttpServletRequest request, @RequestBody String lstMsgId) { System.out.println(lstMsgId); return lstMsgId; }
请求参数为:"90c8c36f23a94c1487851129aa47d690/90c8c36f23a94c1487851129aa47d690"。Postman直接发送该参数可以正常工作,但使用Hutool工具类发送时,却出现以下错误:
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: ...; nested exception is com.alibaba.fastjson.JSONException: ...
问题根源在于Spring Boot默认使用application/json处理@RequestBody参数。当参数被双引号包裹时,Spring Boot将其视为JSON格式。 因此,对于非JSON字符串参数,我们需要显式指定请求的Content-Type。
解决方法是将请求的Content-Type设置为text/plain。这样,Spring Boot就不会尝试将其解析为JSON。
使用Hutool工具类修改后的代码如下:
HttpRequest request = HttpRequest.post(url); request.header("Content-Type", "text/plain"); request.body("90c8c36f23a94c1487851129aa47d690/90c8c36f23a94c1487851129aa47d690"); String responseJsonStr = request.execute().body();
通过设置Content-Type: text/plain,@RequestBody注解即可正确接收非JSON格式的字符串参数。 这避免了不必要的JSON解析错误,确保了接口的稳定性和可靠性。
以上就是如何让SpringBoot中的@RequestBody注解正确接收非JSON格式的字符串参数?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号