美文网首页
OkHttp(一):调用流程

OkHttp(一):调用流程

作者: ti天梦 | 来源:发表于2018-07-16 11:20 被阅读0次

OkHttp(一):调用流程

调用流程图

先给图,如图所示,为整个OKhttp的调用流程。

1、通过Builder模式生产OkHttpClient实例;Builder里面配置各种参数;

Builder参数

2、所有的请求都是封装为一个Request,然后生成一个Call对象。Call是一个接口,实际生成的是RealCall对象;

Request参数 生成实际的RealCall对象

3、RealCall里面有两个方法,excuted和enqueue。excuted为同步调用,enqueue为异步调用。两个API均会进入dispather中;

同步异步方法

4、dispather中有三个队列,runningSyncCalls(正在执行的同步请求队列)、runningAsyncCalls(正在执行的异步请求队列)、readyAsyncCalls(等待中的异步请求队列);还有一个线程池(下一篇讲解)

三个请求队列

5、excuted同步方法,会调用dispatcher的excuted,dispatcher会将这个Call添加进runningSyncCalls队列,执行。之后会调用getResponseWithInterceptorChain;

RealCall的execute方法 dispatcher中的executed方法

6、enqueue异步方法,会通过该Call生成一个AsyncCall对象,AsyncCall是RealCall的内部类,继承自NamedRunnable继承自Runnable。调用dispatcher的enqueue,将该AsyncCall传递给dispatcher;然后调用该判断。如果为true,将该AsyncCall添加到runningAsyncCalls队列,并加入到线程池执行;如果为false,则添加进readyAsyncCalls队列,排队等待;

RealCall的enqueue方法 diapatcher中的enqueue方法 内部类AsyncCall

7、不管是同步还是异步,内部都会调用getResponseWithInterceptorChain方法来获取Response;

AsyncCall对象的execute方法

8、getResponseWithInterceptorChain内部,装配所有的Interceptor;

getResponseWithInTerceptorChain

9、调用Chain.proceed方法,实际调用的是RealInterceptorChain.proceed方法;用责任链模式,遍历所有的Interceptor获取具体的Response

proceed方法

10、其中:Interceptors为应用拦截器、

retryAndFollowUpInterceptor为重试和重定向处理器、

BridgeInterceptor为桥接连接器(用户级别的Response、Request <==> http级别的Response、Request   之间的互相转换)、

CacheInterceptor为http缓存处理机制、

ConnectInterceptor创建连接,对http请求和相应进行编解码、

NetworkInterception为用户自定义的网络级别拦截器、

CallServerInterceptor具体的连接请求

相关文章

网友评论

      本文标题:OkHttp(一):调用流程

      本文链接:https://www.haomeiwen.com/subject/plivpftx.html