好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

RestTemplate实现多种底层HTTP客户端类库的切换用法

本文是精讲RestTemplate第2篇,前篇的blog访问地址如下:

RestTemplate在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在Spring或非Spring环境下使用精讲

2.1.切换为okHTTP

首先通过maven坐标将okHTTP的包引入到项目中来

?

1

2

3

4

5

< dependency >

     < groupId >com.squareup.okhttp3</ groupId >

     < artifactId >okhttp</ artifactId >

     < version >4.7.2</ version >

</ dependency >

如果是spring 环境下通过如下方式使用OkHttp3ClientHttpRequestFactory初始化RestTemplate bean对象。

?

1

2

3

4

5

6

7

8

@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方法类似、不再赘述。

?

1

2

3

4

5

< dependency >

     < groupId >org.apache.httpcomponents</ groupId >

     < artifactId >httpclient</ artifactId >

     < version >4.5.12</ version >

</ dependency >

使用HttpComponentsClientHttpRequestFactory初始化RestTemplate bean对象

?

1

2

3

4

5

@Bean ( "httpClient" )

public RestTemplate httpClientRestTemplate(){

     RestTemplate restTemplate = new RestTemplate( new HttpComponentsClientHttpRequestFactory());

     return restTemplate;

}

以上就是RestTemplate实现多种底层HTTP客户端类库的切换精讲的详细内容,更多关于RestTemplate底层HTTP客户端类库切换的资料请关注其它相关文章!

原文链接:https://zimug.blog.csdn.net/article/details/107755368

查看更多关于RestTemplate实现多种底层HTTP客户端类库的切换用法的详细内容...

  阅读:12次