http调用之RestTemplate
核心方法为org.springframework.web.client.RestTemplate.doExecute(URI, HttpMethod, RequestCallback, ResponseExtractor<T>)
方法内容如下:

其中,重点在下面这三行:

ClientHttpRequest是http请求调用的抽象,具体实现有jdk自带的以及apache的httpclient,实现类如下:

simple开头的是使用jdk自带的net操作,Components的底层是httpclient操作。
AbstractBufferingClientHttpRequest为缓存requestbody的基类,内部bufferedOutput保存了requestbody的内容,避免流的二次读取会导致读取不到数据。
那么,到底是哪里给这个ByteArrayOutputStream对象赋值的呢?答案就在org.springframework.web.client.RestTemplate.HttpEntityRequestCallback,注释讲得很清楚:

在上面讲到的重点强调的三行代码中,调用了org.springframework.web.client.RestTemplate.HttpEntityRequestCallback.doWithRequest(ClientHttpRequest)方法,这个方法里面根据requestContentType等信息,在HttpMessageConverters列表中寻找合适的HttpMessageConverter,利用这些httpMessageConverter天然的write方法将requestBody的内容经过处理转换写入入参HttpOutputMessage对应的getBody方法返回的OutputStream流中。然而,我们这里的ClientHttpRequest接口继承自HttpOutputMessage,AbstractClientHttpRequest的getBody实现调用子类的getBodyInternal方法,重点来了,AbstractBufferingClientHttpRequest的getBodyInternal返回的就是bufferedOutput,也就是缓存的ByteArrayOutputStream。到这里,缓存的requestbody数据有了。再啰嗦一句,使用HttpEntityRequestCallback的都是post请求的,get请求用的AcceptHeaderRequestCallback。
那么,问题来了,什么情况下会用这个缓存数据呢?我们看下AbstractBufferingClientHttpRequest的子类就知道了。
这里,又要回到刚刚的三行重点代码,doExecute的时候调用createRequest方法返回ClientHttpRequest,实际调用父类方法org.springframework.http.client.support.HttpAccessor.createRequest(URI, HttpMethod):
org.springframework.http.client.support.InterceptingHttpAccessor.getRequestFactory()方法如下:

如果设置了拦截器就返回InterceptingClientHttpRequestFactory,并将restTemplete原有的RequestFactory作为参数传入。
该factory创建的是org.springframework.http.client.InterceptingClientHttpRequest,该类重写的executeInternal方法通过内部类InterceptingRequestExecution实现interceptors顺序执行,当迭代结束后,通过之前传进来的requestFactory创建ClientHttpRequest,并将body copy给刚刚创建的request的body,并调用execute方法,方法内容如下:

其实,InterceptingClientHttpRequest本身就带有requestbody缓存copy功能,所以无需在创建restTemplate时包装一个BufferingClientHttpRequestFactory,直接使用HttpComponentsClientHttpRequestFactory即可,这个factory自带bufferRequestBody功能。
相信大部分同学在项目中都是选择apache的httpclient发送http请求,所以,这里我们重点看下org.springframework.http.client.HttpComponentsClientHttpRequestFactory,我们看下createRequest方法:
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
HttpClient client = getHttpClient();
HttpUriRequest httpRequest = createHttpUriRequest(httpMethod, uri);
postProcessHttpRequest(httpRequest);
HttpContext context = createHttpContext(httpMethod, uri);
if (context == null) {
context = HttpClientContext.create();
}
// Request configuration not set in the context
if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) {
// Use request configuration given by the user, when available
RequestConfig config = null;
if (httpRequest instanceof Configurable) {
config = ((Configurable) httpRequest).getConfig();
}
if (config == null) {
config = createRequestConfig(client);
}
if (config != null) {
context.setAttribute(HttpClientContext.REQUEST_CONFIG, config);
}
}
// 默认情况下bufferRequestBody为true,创建使用缓存的body作为请求体
if (this.bufferRequestBody) {
return new HttpComponentsClientHttpRequest(client, httpRequest, context);
}
else {
return new HttpComponentsStreamingClientHttpRequest(client, httpRequest, context);
}
}
看下上面注释的类的下面方法org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpHeaders, byte[]):

这个类也是继承自AbstractBufferingClientHttpRequest,所以刚刚InterceptingRequestExecution迭代结束后getBody返回的就是缓存的bufferedOutput,到这里执行的时候就将bufferedOutput作为ByteArrayEntity发送http请求。至此,结束。
http调用之RestTemplate的更多相关文章
- SpringCloud实现服务间调用(RestTemplate方式)
上一篇文章<SpringCloud搭建注册中心与服务注册>介绍了注册中心的搭建和服务的注册,本文将介绍下服务消费者调用服务提供者的过程. 本文目录 一.服务调用流程二.服务提供者三.服务消 ...
- spring boot / cloud (八) 使用RestTemplate来构建远程调用服务
spring boot / cloud (八) 使用RestTemplate来构建远程调用服务 前言 上周因家里突发急事,请假一周,故博客没有正常更新 RestTemplate介绍: RestTemp ...
- SpringBoot系列(一)RestTemplate
作为springBoot的开篇系列,RestTemplate只能表示我只是个意外 what RestTemplate是spring提供的用于访问rest服务的客户端(其实类似Apache的HttpCl ...
- Spring Boot使用RestTemplate消费REST服务的几个问题记录
我们可以通过Spring Boot快速开发REST接口,同时也可能需要在实现接口的过程中,通过Spring Boot调用内外部REST接口完成业务逻辑. 在Spring Boot中,调用REST Ap ...
- 如何使用RestTemplate访问restful服务
一. 什么是RestTemplate 传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient.不过此种方法使用起来太过繁琐.spring提供了一种简单便捷的模板类 ...
- springcloud-feign组件实现声明式的调用
11.使用feign实现声明式的调用 使用RestTemplate+ribbon已经可以完成对服务端负载均衡的调用,为什么还要使用feign? @RequestMapping("/hi&qu ...
- Spring Cloud(三):声明式调用
声明式服务调用 前面在使用spring cloud时,通常都会利用它对RestTemplate的请求拦截来实现对依赖服务的接口调用,RestTemplate实现了对http的请求封装处理,形成了一套模 ...
- SpringCloud系列-利用Feign实现声明式服务调用
上一篇文章<手把手带你利用Ribbon实现客户端的负载均衡>介绍了消费者通过Ribbon调用服务实现负载均衡的过程,里面所需要的参数需要在请求的URL中进行拼接,但是参数太多会导致拼接字符 ...
- RestTemplate相关组件:ClientHttpRequestInterceptor【享学Spring MVC】
每篇一句 做事的人和做梦的人最大的区别就是行动力 前言 本文为深入了解Spring提供的Rest调用客户端RestTemplate开山,对它相关的一些组件做讲解. Tips:请注意区分RestTemp ...
随机推荐
- Kubernetes 与 Helm:使用同一个 Chart 部署多个应用
k8s 集群搭建好了,准备将 docker swarm 上的应用都迁移到 k8s 上,但需要一个一个应用写 yaml 配置文件,不仅要编写 deployment.yaml 还要编写 service.y ...
- 4.万能的Map+模糊查询
万能的Map 当数据或者属性很多的时候,可以选择性的单独改变密码或者用户名等等 UserMapper.java int updateUserByMap(Map<String,Object> ...
- 自己常用的Linux命令和Hadoop命令
记录自己常用的Linux命令: ss的启动命令:ssserver -c /etc/shadowsocks.json jupyter notebook的启动命令:jupyter notebook --a ...
- Platform device/driver注册过程
Platform是一种虚拟总线,Platform机制将设备本身的资源注册进内核,有内核统一管理,在驱动程序使用这些资源时使用统一的接口,这样提高了程序的可移植性. Linux的大部分设备驱动都可以使用 ...
- django removing hardcoded URLs in template --- 使用变量,把url放在变量中 {% url 'namespace:name' %}
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^votes/', include("polls.urls", na ...
- iOS 优化ipa包,减小安装包大小
https://www.jianshu.com/p/a49d59b01669 项目打包之后.ipa包的大小是118.9M,上传到App Store后iPhone6s上显示85.5M,下载时间太长,所以 ...
- linux下windows访问samba服务器
今天学习windows如何访问linux的共享文件. 开通samba服务,首先需要在linux下安装samba程序包,又再次使用光盘镜像挂载: [root@localhost home]# mount ...
- Bugku-CTF加密篇之贝斯家族(@iH<,{bdR2H;i6*Tm,Wx2izpx2!)
贝斯家族 @iH<,{bdR2H;i6*Tm,Wx2izpx2!
- Codeforces Round #601 (Div. 2)D(蛇形模拟)
#define HAVE_STRUCT_TIMESPEC #include<bits/stdc++.h> using namespace std; vector<char>an ...
- 【PAT甲级】1079 Total Sales of Supply Chain (25 分)
题意: 输入一个正整数N(<=1e5),表示共有N个结点,接着输入两个浮点数分别表示商品的进货价和每经过一层会增加的价格百分比.接着输入N行每行包括一个非负整数X,如果X为0则表明该结点为叶子结 ...