桦甸市建设局网站,2019年做网站,保网官网,怎么样做国际网站生意RestTemplate介绍
RestTemplate是Spring提供的用于访问RESTful服务的客户端#xff0c;RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。RestTemplate默认依赖JDK提供http连接的能力#xff08;HttpURLConnection#xff09;#xff0c;…RestTemplate介绍
RestTemplate是Spring提供的用于访问RESTful服务的客户端RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。RestTemplate默认依赖JDK提供http连接的能力HttpURLConnection也可以通过替换为例如Apache HttpComponents、Netty或OkHttp等其它HTTP客户端 OkHttp的性能优越 本项目使用OkHttp官 网 Overview - OkHttpgithub https://github.com/square/okhttp。 RestTemplate效果测试
1.依赖
dependencygroupIdcom.squareup.okhttp3/groupIdartifactIdokhttp/artifactId
/dependency
2.配置
Bean
public RestTemplate restTemplate() {return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}
3.测试类
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.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;RunWith(SpringRunner.class)
SpringBootTest
public class TemplateTest {Autowiredprivate RestTemplate restTemplate;Testpublic void test(){String url http://www.baidu.com;ResponseEntityString forEntity restTemplate.getForEntity(url, String.class);System.out.println(网页结果forEntity.getBody());}} 网页内容中中文乱码解决方案
原因
当RestTemplate默认使用String存储body内容时默认使用ISO_8859_1字符集。
解决
配置StringHttpMessageConverter 消息转换器使用utf-8字符集。
修改RestTemplate的定义方法 Beanpublic RestTemplate restTemplate(){RestTemplate restTemplate new RestTemplate(new OkHttp3ClientHttpRequestFactory());//获取配置转换器ListHttpMessageConverter? messageConverters restTemplate.getMessageConverters();//设置编码格式messageConverters.set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));//将转换器修改后的对象再赋值回去对原来对象属性进行修改restTemplate.setMessageConverters(messageConverters);return restTemplate;}
OkHttp3ClientHttpRequestFactory()
Ctrl单击点进去查看源码 继续跟进 光标在接口上ClientHttpRequestFactory 快捷键CtrlAlt鼠标单击查看实现类或者快捷键Ctrlh即可看到OkHttp3ClientHttpRequestFactory()