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

相关推荐
2501_915921433 小时前
iOS IPA 混淆实测分析:从逆向视角验证加固效果与防护流程
websocket·网络协议·tcp/ip·http·网络安全·https·udp
2501_915918413 小时前
打造可观测的 iOS CICD 流程:调试、追踪与质量保障全记录
websocket·网络协议·tcp/ip·http·网络安全·https·udp
小菜鸡95276 小时前
http、SSL、TLS、https、证书
http·https·证书·ssl·tls
2501_915909067 小时前
调试 WebView 旧资源缓存问题:一次从偶发到复现的实战经历
websocket·网络协议·tcp/ip·http·网络安全·https·udp
小湘西7 小时前
Apache HttpClient 的请求模型和 I/O 类型
java·http·apache
cliffordl8 小时前
MCP 传输机制(Streamable HTTP)
网络·网络协议·http
2501_915921439 小时前
请求未达服务端?iOS端HTTPS链路异常的多工具抓包排查记录
websocket·网络协议·tcp/ip·http·网络安全·https·udp
妮妮喔妮10 小时前
HTTP中常见的Content-Type
网络·网络协议·http
危险、11 小时前
RabbitMQ 通过HTTP API删除队列命令
分布式·http·rabbitmq
超人不会飛11 小时前
就着HTTP聊聊SSE的前世今生
前端·javascript·http