如何在SpringBoot中使用@RequestBody注解正確接收非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字符串參數。

? 版權聲明
THE END
喜歡就支持一下吧
點贊14 分享