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()

相关推荐
csdn_aspnet27 分钟前
在 ASP.NET Core 中使用自定义属性实现 HTTP 请求和响应加密
http·asp.net·.netcore
不知名。。。。。。。。2 小时前
HTTP协议
网络·网络协议·http
冉佳驹2 小时前
Qt【第六篇】 ——— 事件处理、多线程、网络与文件等操作详解
qt·http·udp·tcp·事件·多线程与互斥锁
一条闲鱼_mytube4 小时前
【深入理解】HTTP/3 与 QUIC 协议:从原理到 Go 语言实战
网络协议·http·golang
EmbeddedCore5 小时前
物联网通讯协议怎么选?MQTT、TCP、UDP、HTTP、HTTPS全面解析
物联网·tcp/ip·http
深念Y6 小时前
前端实时通信技术:HTTP轮询、SSE、WebSocket、WebRTC
前端·websocket·网络协议·http·实时互动·轮询·实时通信
fe7tQnVan17 小时前
浅谈HTTP中Get与Post的区别
网络·网络协议·http
pl4H522a61 天前
istio初探以及解决http-426的问题
http·kubernetes·istio
Strange_Head1 天前
《Linux系统网络协议》用 C 语言写一个最小 HTTP Server 与 Client——网络篇
网络·网络协议·http
不会写DN1 天前
让 gRPC 服务同时支持 HTTP/JSON 的gRPC-Gateway
http·json·gateway