本文主要研究一下RestTemplate对HttpClient的适配
org/springframework/http/client/ClientHttpRequestFactory.java
spring-web定义了ClientHttpRequestFactory接口,它定义了一个createRequest方法
org/springframework/http/client/HttpComponentsClientHttpRequestFactory.java
HttpComponentsClientHttpRequestFactory实现了ClientHttpRequestFactory及DisposableBean接口;createRequest方法先拿到httpClient,然后创建createHttpUriRequest,设置RequestConfig,针对bufferRequestBody的场景HttpComponentsClientHttpRequest,否则创建HttpComponentsStreamingClientHttpRequest;destroy方法主要是关闭httpClient
org/springframework/http/client/ClientHttpRequest.java
ClientHttpRequest接口定义了execute方法,它返回ClientHttpResponse
org/springframework/http/client/HttpComponentsClientHttpRequest.java
HttpComponentsClientHttpRequest继承了AbstractBufferingClientHttpRequest,其executeInternal方法调用httpClient.execute,然后返回HttpComponentsClientHttpResponse
org/springframework/http/client/HttpComponentsStreamingClientHttpRequest.java
HttpComponentsStreamingClientHttpRequest继承了AbstractClientHttpRequest,实现了StreamingHttpOutputMessage接口,其getBodyInternal抛出UnsupportedOperationException,其executeInternal方法创建的是StreamingHttpEntity,然后执行httpClient.execute(this.httpRequest, this.httpContext),最后返回HttpComponentsClientHttpResponse
org/springframework/http/client/ClientHttpResponse.java
ClientHttpResponse接口定义了getStatusCode、getRawStatusCode、getStatusText、close方法
org/springframework/http/client/HttpComponentsClientHttpResponse.java
HttpComponentsClientHttpResponse继承了AbstractClientHttpResponse,其getBody方法返回的是httpResponse.getEntity().getContent()或者StreamUtils.emptyInput(),其close方法主要是执行EntityUtils.consume(this.httpResponse.getEntity())以及((Closeable) this.httpResponse).close()
spring-web定义了ClientHttpRequestFactory接口,它定义了一个createRequest方法,HttpComponentsClientHttpRequestFactory就是RestTemplate对HttpClient的适配,其通过HttpComponentsClientHttpRequest或者HttpComponentsStreamingClientHttpRequest,将HttpClient的request适配为了spring-web的ClientHttpRequest,将response通过HttpComponentsClientHttpResponse适配为spring-web的ClientHttpResponse。