在RestTemplate基础用法博文中,post json表单时,会发现存在中文乱码问题,本文主要介绍对应的解决方案
I. 中文乱码Fix
1. “罪魁祸首”
场景复现
1 | /** |
输出结果如下:
1 | (json post res: params: {} | DemoRest.ReqBody(name=???Blog, age=20) |
原因定位
RestTemplate中存在一个HttpMessageConverter
列表的属性成员,而HttpMessageConverter
主要的职责就是消息转码
导致我们中文乱码的一个关键点在于StringHttpMessageConverter
采用的默认编码格式为StandardCharsets.ISO_8859_1
2. 指定StringHttpMessageConverter编码
既然是因为StringHttpMessageConverter
的默认编码不是UTF-8,那么将它手动改成utf-8不就over了么
1 | /** |
测试输出如:
1 | (json post res: params: {} | DemoRest.ReqBody(name=一灰灰Blog, age=20) |
3. 传参POJO
在看RestTemplate
的HttpMessageConvert
时,会看到默认提供了一个MappingJackson2HttpMessageConverter
,那么我们直接传参POJO,走Jackson序列化,是不是也可以解决中文乱码呢?
1 |
|
输出结果如下
1 | (json post DO res: params: {} | DemoRest.ReqBody(name=一灰灰Blog, age=20) |
说明:上面的InnerParam对象改成HashMap,也是ok的
II. 其他
0. 项目&系列博文
博文
源码
- 工程:https://github.com/liuyueyi/spring-boot-demo
- 源码: https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/221-web-resttemplate
1. 一灰灰Blog
尽信书则不如,以上内容,纯属一家之言,因个人能力有限,难免有疏漏和错误之处,如发现bug或者有更好的建议,欢迎批评指正,不吝感激
下面一灰灰的个人博客,记录所有学习和工作中的博文,欢迎大家前去逛逛
- 一灰灰Blog个人博客 https://blog.hhui.top
- 一灰灰Blog-Spring专题博客 http://spring.hhui.top
Related Issues not found
Please contact @liuyueyi to initialize the comment