Android - 剖析OKHttp(3)- 拦截器

2020-11-06  本文已影响0人  杨0612

源码分析基于 3.14.4

拦截器的思想

分层的思想,将一个复杂的网络请求(请求头填充、缓存、重试、建立连接、发起请求)分割成小模块,每个模块负责提供一个能力,符合单一职责原则,也是为了便于维护,不至于修改其中一个节点而影响别的节点,很好地控制影响范围。

发起请求的过程也是执行拦截器的过程

//AsyncCall类中
  Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List<Interceptor> interceptors = new ArrayList<>();
    interceptors.addAll(client.interceptors());//1
    interceptors.add(new RetryAndFollowUpInterceptor(client));//2
    interceptors.add(new BridgeInterceptor(client.cookieJar()));//3
    interceptors.add(new CacheInterceptor(client.internalCache()));//4
    interceptors.add(new ConnectInterceptor(client));//5
    if (!forWebSocket) {
      interceptors.addAll(client.networkInterceptors());//6
    }
    interceptors.add(new CallServerInterceptor(forWebSocket));//7

    Interceptor.Chain chain = new RealInterceptorChain(interceptors, transmitter, null, 0,
        originalRequest, this, client.connectTimeoutMillis(),
        client.readTimeoutMillis(), client.writeTimeoutMillis());//8
      Response response = chain.proceed(originalRequest);
      return response;
  }

以上分析有不对的地方,请指出,互相学习,谢谢哦!

上一篇 下一篇

猜你喜欢

热点阅读