Resttemplate请求中文乱码
1 概述
解决RestTemplate请求中文乱码问题。
如果是StringHttpMessageConverter,则修改器默认字符集:ISO-8859-1为utf-8,对于postForObject 底层均采用了MappingJackson2HttpMessageConverter来处理请求。
对于String格式提交数据时,底层其实采用的是StringHttpMessageConverter来处理请求。
1.1 RestTemplateUtil
package com.kikop.localribbonclient.util;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.Charset;
import java.util.List;
/**
-
@author kikop
-
@version 1.0
-
@project Name: myribboninaction
-
@file Name: RestTemplateUtil
-
@desc 功能描述 解决RestTemplate请求中文乱码
-
@date 2020/2/9
-
@time 14:46
-
@by IDE: IntelliJ IDEA
-
@sample https://blog.csdn.net/mryang125/article/details/80963280
*/
public class RestTemplateUtil {
/**
* 获取restTemplate实例
*
* @param charset utf-8
* @return
*/
public static RestTemplate getInstance(String charset) {
// 如果是StringHttpMessageConverter,则修改器默认字符集:ISO-8859-1为utf-8
// postForObject 底层均采用了MappingJackson2HttpMessageConverter来处理请求
// String格式提交数据时,底层其实采用的是StringHttpMessageConverter来处理请求
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> list = restTemplate.getMessageConverters();
for (HttpMessageConverter<?> httpMessageConverter : list) {
if (httpMessageConverter instanceof StringHttpMessageConverter) {
((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName(charset));
break;
}
}
return restTemplate;
}
}
1.2使用
package com.kikop.localribbonclient.controller;
import com.kikop.localribbonclient.util.RestTemplateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
-
@author kikop
-
@version 1.0
-
@project Name: myribboninaction
-
@file Name: RibbonController
-
@desc 功能描述
-
@date 2020/2/9
-
@time 11:02
-
@by IDE: IntelliJ IDEA
*/
@RestController
public class RibbonController {
@Autowired
private LoadBalancerClient loadBalancer;
@GetMapping("/testRibbon")
public String testRibbon() {
ServiceInstance instance = loadBalancer.choose("stores");
return instance.getHost() + ":" + instance.getPort();
}
@GetMapping("/testReqDomain")
public String testReqDomain() {
ServiceInstance instance = loadBalancer.choose("stores");
String reqServerUrl = String.format("http://%s:%d", instance.getHost(), instance.getPort());
System.out.println(reqServerUrl);
RestTemplate restTemplate = RestTemplateUtil.getInstance("utf-8");
return restTemplate.getForObject(reqServerUrl, String.class);
}
}
参考
- 初探RestTemplate--解决中文乱码问题
<u>https://blog.csdn.net/mryang125/article/details/80963280</u>
网友评论