1.RestTemplate 访问 Restfull 接口: 中文乱码 + 返回数据格式为 xml
Spring Cloud 项目, 肯定会用到组件之间的 Http 通信, 我使用的是 spring 提供的简单便捷的模板类: RestTemplate.
Restfull 接口如下:
Resufull 接口, 分页查询登录日志
请求: restTemplate.getForEntity(routerUrl,String.class,map);
RestTemplate 请求
返回 200, 这个没问题, 重点是: 访问 Restfull 接口竟然返回的是 xml 格式的数据!!! 而且中文还是乱码.
2. 解决中文乱码
其实对于中文乱码的问题我倒是预料到了, 在 restTemplate 的 MessageConverters 集合里加入 StringHttpMessageConverter 就可以了, 代码如下
- RestTemplate restTemplate =new RestTemplate();
- restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
乱码问题解决
3. 解决返回 xml 问题
这个问题比较怪异, 我的项目中有五个组件, 都是 Restfull 接口, 但访问一部分组件返回的是正常的 JSON, 一部分组件返回的是 xml. 分别对每个组件使用 postman 直接访问, 返回的都是正常的 JSON. 那么不出意外, 应该就是 RestTemplate 在捣鬼了.
二话不说, 直接扒源码, 发现了一个可疑的家伙: jackson2XmlPresent, 如图:
原来在 RestTemplate 的 messageConverters 中有这么多成员常驻着, 别的我不管, 这个 jackson2XmlPresent 可是要了命的鬼啊, 虽然我没直接证据证明是它把我的 JSON 转成 xml, 但看着它就来气, 果断弄掉.
等等, 我在项目中用到的是 FastJson,RestTemplate 的 messageConverters 里面没有 FastJson, 作为一个处女座程序员, 怎么能容许你用 jackson 解析我的 FastJson 呢, 果断干掉 jackson, 加入 FastJson, 代码如下:
- RestTemplate restTemplate =new RestTemplate();
- restTemplate.getMessageConverters().clear();
- restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
干掉所有 messageConverters, 加入 FastJsonHttpMessageConverter, 由于 FastJsonHttpMessageConverter 默认字符集就是 UTF8, 因此, 一行代码将中文乱码和 JSON 解析成 xml 的问题一并解决了, 效果如下:
完美
来源: http://www.jianshu.com/p/8be6efeb17b1