RestTemplate

RestTemplate介绍

RestTemplate是Spring提供的用于访问RESTful服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。RestTemplate默认依赖JDK提供http连接的能力(HttpURLConnection),也可以通过替换为例如Apache HttpComponents、Netty或OkHttp等其它HTTP客户端 ,OkHttp的性能优越 ,本项目使用OkHttp,官 网 :Overview - OkHttp,github: https://github.com/square/okhttp

RestTemplate效果测试

1.依赖

java 复制代码
<dependency>
     <groupId>com.squareup.okhttp3</groupId>
     <artifactId>okhttp</artifactId>
</dependency>

2.配置

java 复制代码
@Bean
public RestTemplate restTemplate() {
    return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}

3.测试类

java 复制代码
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 {

    @Autowired
    private RestTemplate restTemplate;

    @Test
    public void test(){
        String url = "http://www.baidu.com";
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
        System.out.println("网页结果:"+forEntity.getBody());
    }

}

网页内容中中文乱码解决方案:

原因:

当RestTemplate默认使用String存储body内容时默认使用ISO_8859_1字符集。

解决:

配置StringHttpMessageConverter 消息转换器,使用utf-8字符集。

修改RestTemplate的定义方法

java 复制代码
  @Bean
    public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());
        //获取配置转换器
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        //设置编码格式
        messageConverters.set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        //将转换器修改后的对象再赋值回去,对原来对象属性进行修改
        restTemplate.setMessageConverters(messageConverters);

        return restTemplate;

    }

OkHttp3ClientHttpRequestFactory()

Ctrl+单击点进去查看源码

继续跟进

光标在接口上ClientHttpRequestFactory

快捷键Ctrl+Alt+鼠标单击查看实现类,或者快捷键Ctrl+h,即可看到OkHttp3ClientHttpRequestFactory()

相关推荐
null_null9991 小时前
宝塔nginx http转https代理
nginx·http·https
冰糖拌面1 小时前
GO写的http服务,清空cookie
服务器·http·golang
爱编程的鱼1 小时前
HTTP 是什么?它是如何工作的
网络·网络协议·http
檐下翻书1732 小时前
Spring Boot 深度剖析:从虚拟线程到声明式 HTTP 客户端,再到云原生最优解
spring boot·http·云原生
雪域迷影13 小时前
C#中通过get请求获取api.open-meteo.com网站的天气数据
开发语言·http·c#·get
2501_9159184116 小时前
HTTP抓包工具推荐,Fiddler使用教程、代理设置与调试技巧详解(含HTTPS配置与实战案例)
http·ios·小程序·https·fiddler·uni-app·webview
Pocker_Spades_A18 小时前
Python快速入门专业版(五十四):爬虫基石:HTTP协议全解析(从请求到响应,附Socket模拟请求)
爬虫·python·http
天玺-vains21 小时前
借助Github Action实现通过 HTTP 请求触发邮件通知
网络协议·http·github
国服第二切图仔1 天前
Rust开发实战之使用 Reqwest 实现 HTTP 客户端请求
开发语言·http·rust
利刃大大1 天前
【高并发服务器:HTTP应用】十四、Util工具类的设计与实现
服务器·http·高并发·项目·cpp