RestTemplate乱码问题描述
RestTemplate是Spring-web提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷的访问远程Http服务的方法,能够大大提高客户端的编写效率。
RestTemplate默认依赖JDK提供http连接的能力(HttpURLConnection),在项目中会通过setRequestFactory方法或构造方法替换为例如 Apache HttpComponents、Netty或OkHttp等其它HTTP library,其中OkHttp的性能优越,使用较多。
在使用 restTemplate.getForEntity方法抓取网页内容时发现返回的内容为乱码,代码如下:
package com.pbteach.test
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.*;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
public class RestTemplateTest {
@Autowired
RestTemplate restTemplate;
//获取网页内容
@Test
public void gethtml(){
//要抓取的网页地址
String url = "http://www.pbteach.com/";
ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
String body = forEntity.getBody();
System.out.println(body);
}
}
问题分析
RestTemplate在消息解析过程中有很多的消息转换器,跟踪源代码,如下:
当RestTemplate默认使用String存储body内容时默认使用ISO_8859_1字符集,如果内容有中文则会乱码。
问题解决
配置StringHttpMessageConverter 消息转换器,使用utf-8字符集。
修改RestTemplate的定义方法
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());
//消息转换器列表
List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
//配置消息转换器StringHttpMessageConverter,并设置utf-8
messageConverters.set(1,
new StringHttpMessageConverter(StandardCharsets.UTF_8));//支持中文字符集,默认ISO-8859-1,支持utf-8
return restTemplate;
}
再次跟踪源代码,StringHttpMessageConverter使用的字符集为utf-8。
重启应用,抓取网页内容,不再乱码了!
版权声明:本文为weixin_44062339原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。