OkHttp(一):调用流程

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具体的连接请求

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容