在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解析錯誤,確保了接口的穩定性和可靠性。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END