Android OkHttp进阶

一、OkHttp框架流程

 

 

整个流程中最重要的两部分是Dispatcher和Interceptor。

  1. Dispatcher事件分发,分为同步队列和异步列两种分发模式:
    1. 同步请求执行过程指在同步队列中添加请求事件 --> 移除请求事件 --> 执行请求事件;
    2. 异步分发指在Dispatcher中有一个线程池ThreadPoolExecutor;
  2. Interceptor拦截器,分为:
    1. RetryAndFollowInterceptor:请求失败重发或者请求重定向拦截器;
    2. BridgeInterceptor:桥拦截器;
    3. CacheInterceptor:缓存拦截器;
    4. ConnectInterceptor:连接池拦截器;
    5. CallServerInterceptor:请求发出拦截器;

二、Dispatcher类任务调度核心模块类

  同步/异步请求都是通过Dispatcher进行调度和管理其状态,也就是说Dispatcher作用就是维护同步或者异步请求的状态,并且维护了一个线程池,用于执行请求。其中,异步的调度比同步要复杂的多。

 

  在Dispatcher类中有三个队列:

1 /** Ready async calls in the order they'll be run. */
2 private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();
3 
4 /** Running asynchronous calls. Includes canceled calls that haven't finished yet. */
5 private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();
6 
7 /** Running synchronous calls. Includes canceled calls that haven't finished yet. */
8 private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();

   源码解析:

三、Interceptor拦截器介绍

 1. 什么是拦截器

  拦截器是OkHttp中提供的一个强大机制,它可以实现网络监听、请求以及响应重写、请求失败重试等功能。无论是同步还是异步都会使用到拦截器这个功能实现网络响应的获取。

  OkHttp拦截器分为两类:

  1. 应用拦截器;

  2. 网络拦截器;

 2. 拦截器链

 

 

 3. 拦截器流程

    1. 在发起请求前使用拦截器对Request进行处理,比如:header;
    2. 调用下一个拦截器获取Response响应,由于拦截器链的概念,只有调用下一个拦截器才能构成拦截器的链条;
    3. 对Response进行处理,返回给上一个拦截器;

四、拦截器详解

1. 重试重写向拦截器 RetryAndFollowUpInterceptor

  1. 创建StreamAllocation对象;
  2. 调用realChain.proceed(...)方法进行网络请求;
  3. 根据异常结果或者响应结果判断是否进行重新请求;
    1       // Attach the prior response if it exists. Such responses never have a body.
    2       if (priorResponse != null) {
    3         response = response.newBuilder()
    4             .priorResponse(priorResponse.newBuilder()
    5                     .body(null)
    6                     .build())
    7             .build();
    8       }

     

  4. 调用下一个拦截器,对Response进行处理,返回给上一个拦截器;

    PS:注意拦截器链的概念,所以必须调用下一个拦截器,否则无法形成拦截器链;

2. 桥拦截器 BridgeInterceptor

  1. 负责将用户构建好的Request请求转化为能进行网络访问的请求;
  2. 将转化好的Request请求进行网络请求;
  3. 将网络请求后后加的响应Response转化为用户可用的Response;

3. 缓存拦截器 CacheInterceptor

 

posted @ 2022-07-21 15:00  naray  阅读(140)  评论(0编辑  收藏  举报