OkHttp(一):调用流程

先给图,如图所示,为整个OKhttp的调用流程。
1、通过Builder模式生产OkHttpClient实例;Builder里面配置各种参数;

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


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

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

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


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



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

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

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

10、其中:Interceptors为应用拦截器、
retryAndFollowUpInterceptor为重试和重定向处理器、
BridgeInterceptor为桥接连接器(用户级别的Response、Request <==> http级别的Response、Request 之间的互相转换)、
CacheInterceptor为http缓存处理机制、
ConnectInterceptor创建连接,对http请求和相应进行编解码、
NetworkInterception为用户自定义的网络级别拦截器、
CallServerInterceptor具体的连接请求
网友评论