您现在的位置是:主页 > news > 和镜像网站做友链/网推接单平台有哪些
和镜像网站做友链/网推接单平台有哪些
admin2025/6/9 3:59:33【news】
简介和镜像网站做友链,网推接单平台有哪些,宁波网站设计方案,包头建设局网站本文是精讲RestTemplate第2篇,前篇的blog访问地址如下: 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用 RestTemplate只是对其他的HTTP客户端的封装,其本身并没有实现HTTP相关的基础功能。其底层实现是可以配置切换的,…
本文是精讲RestTemplate第2篇,前篇的blog访问地址如下:
- 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用
RestTemplate只是对其他的HTTP客户端的封装,其本身并没有实现HTTP相关的基础功能。其底层实现是可以配置切换的,我们本小节就带着大家来看一下RestTemplate底层实现,及如何实现底层基础HTTP库的切换。
一、源码分析
RestTemplate有一个非常重要的类叫做HttpAccessor,可以理解为用于HTTP接触访问的基础类。下图为源码:
从源码中我们可以分析出以下几点信息
- RestTemplate 支持至少三种HTTP客户端库。
- SimpleClientHttpRequestFactory。对应的HTTP库是java JDK自带的HttpURLConnection。
- HttpComponentsAsyncClientHttpRequestFactory。对应的HTTP库是Apache HttpComponents。
- OkHttp3ClientHttpRequestFactory。对应的HTTP库是OkHttp
- java JDK自带的HttpURLConnection是默认的底层HTTP实现客户端
- SimpleClientHttpRequestFactory,即java JDK自带的HttpURLConnection不支持HTTP协议的Patch方法,如果希望使用Patch方法,需要将底层HTTP客户端实现切换为Apache HttpComponents 或 OkHttp
- 可以通过设置setRequestFactory方法,来切换RestTemplate的底层HTTP客户端实现类库。
二、底层实现切换方法
从开发人员的反馈,和网上的各种HTTP客户端性能以及易用程度评测来看,OkHttp 优于 Apache HttpComponents、Apache HttpComponents优于HttpURLConnection。所以我个人更建议大家将底层HTTP实现切换为okHTTP。
以下所讲的切换方法,基于第一篇内容: 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用
2.1.切换为okHTTP
首先通过maven坐标将okHTTP的包引入到项目中来
<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.7.2</version>
</dependency>
如果是spring 环境下通过如下方式使用OkHttp3ClientHttpRequestFactory初始化RestTemplate bean对象。
@Configuration
public class ContextConfig {@Bean("OKHttp3")public RestTemplate OKHttp3RestTemplate(){RestTemplate restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());return restTemplate;}
}
如果是非Spring环境,直接new RestTemplate(new OkHttp3ClientHttpRequestFactory()
之后使用就可以了。
2.2.切换为Apache HttpComponents
与切换为okHTTP方法类似、不再赘述。
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.12</version>
</dependency>
使用HttpComponentsClientHttpRequestFactory初始化RestTemplate bean对象
@Bean("httpClient")
public RestTemplate httpClientRestTemplate(){RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());return restTemplate;
}