OkHttp(一):调用流程

OkHttp(一):调用流程

OkHttp(一):调用流程_第1张图片
调用流程图

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

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


OkHttp(一):调用流程_第2张图片
Builder参数

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


OkHttp(一):调用流程_第3张图片
Request参数


OkHttp(一):调用流程_第4张图片
生成实际的RealCall对象

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


OkHttp(一):调用流程_第5张图片
同步异步方法

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


OkHttp(一):调用流程_第6张图片
三个请求队列

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


OkHttp(一):调用流程_第7张图片
RealCall的execute方法


dispatcher中的executed方法

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


OkHttp(一):调用流程_第8张图片
RealCall的enqueue方法


OkHttp(一):调用流程_第9张图片
diapatcher中的enqueue方法


内部类AsyncCall

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


OkHttp(一):调用流程_第10张图片
AsyncCall对象的execute方法

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


OkHttp(一):调用流程_第11张图片
getResponseWithInTerceptorChain

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


OkHttp(一):调用流程_第12张图片
proceed方法

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

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

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

CacheInterceptor为http缓存处理机制、

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

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

CallServerInterceptor具体的连接请求

你可能感兴趣的:(OkHttp(一):调用流程)