同步请求
image.png
- OkHttpClient -> RealCall -> Dispatcher -> getResponseWithInterceptorChain -> Response
- 这里的核心方法是getResponseWithInterceptorChain,他是RealCall的一个方法负责分发流转Interceptor最后得到Response
- 封装chain的对象,引入所有的拦截器包含(重试,桥接,缓存,连接,获取服务器数据等),每个拦截器处理自己的分内工作逻辑
- 拦截器处理完后调用chain的下一个拦截器处理,直到都处理结束,返回Response
异步请求
image.png
异步请求和同步请求区别
- OKHttpClient封装AsyncCall包含responseCallback, RealCall, Request通过Dispatcher把RealCall加入到readyAsyncCalls的集合中。
- 然后执行Dispatcher的promoteAndExecute方法遍历readyAsyncCalls
- 调用AsyncCall的executeOn方法
- 通过线程池把AsyncCall执行
- 在AsyncCall的run方法执行getResponseWithInterceptorChain和同步走一样的流程,获取到response
- 回调成功后走responseCallback的回调,结束执行dispatcher.finished移除runningAsyncCalls的Callback,执行下一个iterator
拦截器
- RetryAndFollowUpInterceptor 负责失败和重试操作
- BridgeInterceptor 把应用程序的request对象转换为network的request对象,添加一下header参数
- CacheInterceptor 缓存http返回数据,在http code为HTTP_NOT_MODIFIED使用缓存,需要服务端支持
- ConnectInterceptor 创建一个connection连接
- CallServerInterceptor 连上服务器,拿到response