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

相关推荐
moonless02222 天前
FastAPI框架,这一小篇就能搞懂精髓。
http·fastapi
ftpeak3 天前
从零开始使用 axum-server 构建 HTTP/HTTPS 服务
网络·http·https·rust·web·web app
weixin_456904274 天前
使用HTTPS 服务在浏览器端使用摄像头的方式解析
网络协议·http·https
拷贝码农卡卡东4 天前
pre-commit run --all-files 报错:http.client.RemoteDisconnected
网络·网络协议·http
又菜又爱玩呜呜呜~4 天前
go使用反射获取http.Request参数到结构体
开发语言·http·golang
cellurw4 天前
Linux下C语言实现HTTP+SQLite3电子元器件查询系统
linux·c语言·http
希望20174 天前
Golang | http/server & Gin框架简述
http·golang·gin
全栈技术负责人4 天前
前端网络性能优化实践:从 HTTP 请求到 HTTPS 与 HTTP/2 升级
前端·网络·http
Whisper_Yu5 天前
计算机网络(一)基础概念
计算机网络·http·https·信息与通信
emojiwoo5 天前
HTTP 状态码背后的逻辑:从请求到响应的完整流程解析(含完整流程图)
网络·网络协议·http