OkHttp中的拦截器机制源码解析

一、拦截器链流程图

连接器练流程图

二、getResponseWithInterceptorChain 方法

之前说到主要是通过这个方法来返回response那么来看看这个方法里究竟是做了什么呢

 Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List<Interceptor> interceptors = new ArrayList<>();
    interceptors.addAll(client.interceptors());
    interceptors.add(retryAndFollowUpInterceptor);
    interceptors.add(new BridgeInterceptor(client.cookieJar()));
    interceptors.add(new CacheInterceptor(client.internalCache()));
    interceptors.add(new ConnectInterceptor(client));
    if (!forWebSocket) {
      interceptors.addAll(client.networkInterceptors());
    }
    interceptors.add(new CallServerInterceptor(forWebSocket));

    Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
        originalRequest, this, eventListener, client.connectTimeoutMillis(),
        client.readTimeoutMillis(), client.writeTimeoutMillis());

    return chain.proceed(originalRequest);
  }

首先添加自定义配置的拦截器

然后以此添加系统内置的拦截器

然后创建RealInterceptorChain并把这个集合添加进去,这个就是个拦截器链

通过chain.proceed(originalRequest);这个方法执行

proceed这个方法也很重要 可以看一下

 public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
      RealConnection connection) throws IOException {
    if (index >= interceptors.size()) throw new AssertionError();

    calls++;

    // If we already have a stream, confirm that the incoming request will use it.
    if (this.httpCodec != null && !this.connection.supportsUrl(request.url())) {
      throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
          + " must retain the same host and port");
    }

    // If we already have a stream, confirm that this is the only call to chain.proceed().
    if (this.httpCodec != null && calls > 1) {
      throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
          + " must call proceed() exactly once");
    }

    //注意处
    // Call the next interceptor in the chain.
    RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
        connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
        writeTimeout);
    Interceptor interceptor = interceptors.get(index);
    Response response = interceptor.intercept(next);

    // Confirm that the next interceptor made its required call to chain.proceed().
    if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
      throw new IllegalStateException("network interceptor " + interceptor
          + " must call proceed() exactly once");
    }

    // Confirm that the intercepted response isn't null.
    if (response == null) {
      throw new NullPointerException("interceptor " + interceptor + " returned null");
    }

    if (response.body() == null) {
      throw new IllegalStateException(
          "interceptor " + interceptor + " returned a response with no body");
    }

    return response;
  }

这里主要看标注的注意处 这里主要通过index+1创建了下一个拦截器,也就行程了拦截器链

然后通过每个拦截器中都有intercept这个方法,这个方法中返回response然后进行返回。

这里有个流程是很有意思的就是在proceed()方法里会会返回一个Response 而 这个Response是通过intercep()这个方法并传入一个拦截器返回的,而在各个拦截器中又通过传入的拦截器调回去,这也是拦截器流程的核心机制。从而实现了拦截器链,只有所有的拦截器执行完毕后,一个网络请求的响应response 才会被返回。

三、内置拦截器

屏幕快照 2018-01-02 下午5.48.12.png

OkHttp中的内置连接器都基实现了通用的接口

1、RetryAndFollowUpInterceptor 接口重定向拦截器

这个拦截器主要是根据结果判断然后进行重试的拦截器

 @Override public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Call call = realChain.call();
    EventListener eventListener = realChain.eventListener();

    streamAllocation = new StreamAllocation(client.connectionPool(), createAddress(request.url()),
        call, eventListener, callStackTrace);

    int followUpCount = 0;
    Response priorResponse = null;
    while (true) {
      if (canceled) {//注意处1
        streamAllocation.release();
        throw new IOException("Canceled");
      }

      Response response;
      boolean releaseConnection = true;
      try {//注意处2
        response = realChain.proceed(request, streamAllocation, null, null);
        releaseConnection = false;
      } catch (RouteException e) {
        // The attempt to connect via a route failed. The request will not have been sent.
        if (!recover(e.getLastConnectException(), false, request)) {
          throw e.getLastConnectException();
        }
        releaseConnection = false;
        continue;
      } catch (IOException e) {
        // An attempt to communicate with a server failed. The request may have been sent.
        boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
        if (!recover(e, requestSendStarted, request)) throw e;
        releaseConnection = false;
        continue;
      } finally {
        // We're throwing an unchecked exception. Release any resources.
        if (releaseConnection) {
          streamAllocation.streamFailed(null);
          streamAllocation.release();
        }
      }

      // Attach the prior response if it exists. Such responses never have a body.
      if (priorResponse != null) {
        response = response.newBuilder()
            .priorResponse(priorResponse.newBuilder()
                    .body(null)
                    .build())
            .build();
      }

      Request followUp = followUpRequest(response);

      if (followUp == null) {
        if (!forWebSocket) {
          streamAllocation.release();
        }
        return response;
      }

      closeQuietly(response.body());

      if (++followUpCount > MAX_FOLLOW_UPS) {
        streamAllocation.release();
        throw new ProtocolException("Too many follow-up requests: " + followUpCount);
      }

      if (followUp.body() instanceof UnrepeatableRequestBody) {
        streamAllocation.release();
        throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
      }

      if (!sameConnection(response, followUp.url())) {
        streamAllocation.release();
        streamAllocation = new StreamAllocation(client.connectionPool(),
            createAddress(followUp.url()), call, eventListener, callStackTrace);
      } else if (streamAllocation.codec() != null) {
        throw new IllegalStateException("Closing the body of " + response
            + " didn't close its backing stream. Bad interceptor?");
      }

      request = followUp;
      priorResponse = response;
    }
  }

具体分析下流程
首先会创建一个StreamAllocation对象

其实主要看while循环里面的方法,这里是一个死循环来进行尝试,首先会判断是否取消了请求,如果取消进行释放,并抛出异常,如注意处1.

然后主注意处2要进行请求,然后通过catch判断各种需要重新连接的情况,如果重新连接就通过continue直接在进行一遍循环。

当代码可以执行到 followUpRequest 方法就表示这个请求是成功的,但是服务器返回的状态码可能不是 200 ok 的情况,这时还需要对该请求进行检测,其主要就是通过返回码进行判断的,然后如果没问题就会返回respnse并结束循环。

如果没有正常返回结果的话后面会关闭请求还会做一些异常检查,如重新连接的次数是否超过了最大次数之类的。

2、BridgeInterceptor 请求和响应转化拦截器

这个拦截器主要负责设置内容长度,编码方式以及一些压缩等配置,主要是添加头部信息的功能。

 @Override public Response intercept(Chain chain) throws IOException {
    Request userRequest = chain.request();
    Request.Builder requestBuilder = userRequest.newBuilder();

    RequestBody body = userRequest.body();
    if (body != null) {
      MediaType contentType = body.contentType();
      if (contentType != null) {
        requestBuilder.header("Content-Type", contentType.toString());
      }

      long contentLength = body.contentLength();
      if (contentLength != -1) {
        requestBuilder.header("Content-Length", Long.toString(contentLength));
        requestBuilder.removeHeader("Transfer-Encoding");
      } else {
        requestBuilder.header("Transfer-Encoding", "chunked");
        requestBuilder.removeHeader("Content-Length");
      }
    }

    if (userRequest.header("Host") == null) {
      requestBuilder.header("Host", hostHeader(userRequest.url(), false));
    }

    if (userRequest.header("Connection") == null) {
      requestBuilder.header("Connection", "Keep-Alive");
    }

    // If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing
    // the transfer stream.
    boolean transparentGzip = false;
    if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
      transparentGzip = true;
      requestBuilder.header("Accept-Encoding", "gzip");
    }

    List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
    if (!cookies.isEmpty()) {
      requestBuilder.header("Cookie", cookieHeader(cookies));
    }

    if (userRequest.header("User-Agent") == null) {
      requestBuilder.header("User-Agent", Version.userAgent());
    }

    Response networkResponse = chain.proceed(requestBuilder.build());

    HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());

    Response.Builder responseBuilder = networkResponse.newBuilder()
        .request(userRequest);

    if (transparentGzip
        && "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
        && HttpHeaders.hasBody(networkResponse)) {
      GzipSource responseBody = new GzipSource(networkResponse.body().source());
      Headers strippedHeaders = networkResponse.headers().newBuilder()
          .removeAll("Content-Encoding")
          .removeAll("Content-Length")
          .build();
      responseBuilder.headers(strippedHeaders);
      String contentType = networkResponse.header("Content-Type");
      responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
    }

    return responseBuilder.build();
  }

这里通过注意出可以看到其中一个主要的功能就是,如果刚开始我们没有配置一些请求头信息会添加一些默认的请求头信息。

这里还有一个重要功能就是 判断是否需要使用Gzip压缩功能。以及将网络请求回来的响应Response转化为永华可用的response

3、CacheInterceptor 缓存拦截器

@Override public Response intercept(Chain chain) throws IOException {
   Response cacheCandidate = cache != null
       ? cache.get(chain.request())
       : null;

   long now = System.currentTimeMillis();

   CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
   Request networkRequest = strategy.networkRequest;
   Response cacheResponse = strategy.cacheResponse;

   if (cache != null) {
     cache.trackResponse(strategy);
   }

   if (cacheCandidate != null && cacheResponse == null) {
     closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
   }

   // If we're forbidden from using the network and the cache is insufficient, fail.
   if (networkRequest == null && cacheResponse == null) {
     return new Response.Builder()
         .request(chain.request())
         .protocol(Protocol.HTTP_1_1)
         .code(504)
         .message("Unsatisfiable Request (only-if-cached)")
         .body(Util.EMPTY_RESPONSE)
         .sentRequestAtMillis(-1L)
         .receivedResponseAtMillis(System.currentTimeMillis())
         .build();
   }

   // If we don't need the network, we're done.
   if (networkRequest == null) {
     return cacheResponse.newBuilder()
         .cacheResponse(stripBody(cacheResponse))
         .build();
   }

   Response networkResponse = null;
   try {
     networkResponse = chain.proceed(networkRequest);
   } finally {
     // If we're crashing on I/O or otherwise, don't leak the cache body.
     if (networkResponse == null && cacheCandidate != null) {
       closeQuietly(cacheCandidate.body());
     }
   }

   // If we have a cache response too, then we're doing a conditional get.
   if (cacheResponse != null) {
     if (networkResponse.code() == HTTP_NOT_MODIFIED) {
       Response response = cacheResponse.newBuilder()
           .headers(combine(cacheResponse.headers(), networkResponse.headers()))
           .sentRequestAtMillis(networkResponse.sentRequestAtMillis())
           .receivedResponseAtMillis(networkResponse.receivedResponseAtMillis())
           .cacheResponse(stripBody(cacheResponse))
           .networkResponse(stripBody(networkResponse))
           .build();
       networkResponse.body().close();

       // Update the cache after combining headers but before stripping the
       // Content-Encoding header (as performed by initContentStream()).
       cache.trackConditionalCacheHit();
       cache.update(cacheResponse, response);
       return response;
     } else {
       closeQuietly(cacheResponse.body());
     }
   }

   Response response = networkResponse.newBuilder()
       .cacheResponse(stripBody(cacheResponse))
       .networkResponse(stripBody(networkResponse))
       .build();

   if (cache != null) {
     if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
       // Offer this request to the cache.
       CacheRequest cacheRequest = cache.put(response);
       return cacheWritingResponse(cacheRequest, response);
     }

     if (HttpMethod.invalidatesCache(networkRequest.method())) {
       try {
         cache.remove(networkRequest);
       } catch (IOException ignored) {
         // The cache cannot be written.
       }
     }
   }

   return response;
 }

主要流程,先判断是否有缓存。然后如果缓存不可用会关闭,然后在会判断网络禁止的话和缓存都不可用的话会创建一个响应返回504

   // If we're forbidden from using the network and the cache is insufficient, fail.
    if (networkRequest == null && cacheResponse == null) {
      return new Response.Builder()
          .request(chain.request())
          .protocol(Protocol.HTTP_1_1)
          .code(504)
          .message("Unsatisfiable Request (only-if-cached)")
          .body(Util.EMPTY_RESPONSE)
          .sentRequestAtMillis(-1L)
          .receivedResponseAtMillis(System.currentTimeMillis())
          .build();
    }

如果前面的条件都不符合,会读取网络结果也就是会跳转到下一个拦截器, if (networkResponse.code() == HTTP_NOT_MODIFIED) 这里会判断如果是304的话使用缓存,还会对缓存进行比对和更新。然后并返回response。在这之前会先判断cacheResponse是否为空,如果为空则走后面的代码,会创建一个response。

4、ConnectInterceptor 网络连接拦截器

@Override public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Request request = realChain.request();
    StreamAllocation streamAllocation = realChain.streamAllocation();

    // We need the network to satisfy this request. Possibly for validating a conditional GET.
    boolean doExtensiveHealthChecks = !request.method().equals("GET");
    HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);
    RealConnection connection = streamAllocation.connection();

    return realChain.proceed(request, streamAllocation, httpCodec, connection);
  }

这里的StreamAllocation其实是在重定向拦截器中创建,但是他传入到ConnectInterceptor中进行使用。然后会通过streamAllocation来创建httpCodec,httpCodec用来编码request和解码response。然后会通过streamAllocation.connection();来创建一个RealConnection,RealConnection主要来进行实际的网络传输。然后还是通过proceed方法传入到下一个拦截器。

5、CallServerInterceptor

这个拦截器是拦截器链中最后一个拦截器,是真正的发起请求和处理返回响应的拦截器。

@Override public Response intercept(Chain chain) throws IOException {
   RealInterceptorChain realChain = (RealInterceptorChain) chain;
   HttpCodec httpCodec = realChain.httpStream();
   StreamAllocation streamAllocation = realChain.streamAllocation();
   RealConnection connection = (RealConnection) realChain.connection();
   Request request = realChain.request();

   long sentRequestMillis = System.currentTimeMillis();

   realChain.eventListener().requestHeadersStart(realChain.call());
   httpCodec.writeRequestHeaders(request);
   realChain.eventListener().requestHeadersEnd(realChain.call(), request);

   Response.Builder responseBuilder = null;
   if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
     // If there's a "Expect: 100-continue" header on the request, wait for a "HTTP/1.1 100
     // Continue" response before transmitting the request body. If we don't get that, return
     // what we did get (such as a 4xx response) without ever transmitting the request body.
     if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
       httpCodec.flushRequest();
       realChain.eventListener().responseHeadersStart(realChain.call());
       responseBuilder = httpCodec.readResponseHeaders(true);
     }

     if (responseBuilder == null) {
       // Write the request body if the "Expect: 100-continue" expectation was met.
       realChain.eventListener().requestBodyStart(realChain.call());
       long contentLength = request.body().contentLength();
       CountingSink requestBodyOut =
           new CountingSink(httpCodec.createRequestBody(request, contentLength));
       BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);

       request.body().writeTo(bufferedRequestBody);
       bufferedRequestBody.close();
       realChain.eventListener()
           .requestBodyEnd(realChain.call(), requestBodyOut.successfulCount);
     } else if (!connection.isMultiplexed()) {
       // If the "Expect: 100-continue" expectation wasn't met, prevent the HTTP/1 connection
       // from being reused. Otherwise we're still obligated to transmit the request body to
       // leave the connection in a consistent state.
       streamAllocation.noNewStreams();
     }
   }

   httpCodec.finishRequest();

   if (responseBuilder == null) {
     realChain.eventListener().responseHeadersStart(realChain.call());
     responseBuilder = httpCodec.readResponseHeaders(false);
   }

   Response response = responseBuilder
       .request(request)
       .handshake(streamAllocation.connection().handshake())
       .sentRequestAtMillis(sentRequestMillis)
       .receivedResponseAtMillis(System.currentTimeMillis())
       .build();

   realChain.eventListener()
       .responseHeadersEnd(realChain.call(), response);

   int code = response.code();
   if (forWebSocket && code == 101) {
     // Connection is upgrading, but we need to ensure interceptors see a non-null response body.
     response = response.newBuilder()
         .body(Util.EMPTY_RESPONSE)
         .build();
   } else {
     response = response.newBuilder()
         .body(httpCodec.openResponseBody(response))
         .build();
   }

   if ("close".equalsIgnoreCase(response.request().header("Connection"))
       || "close".equalsIgnoreCase(response.header("Connection"))) {
     streamAllocation.noNewStreams();
   }

   if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
     throw new ProtocolException(
         "HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
   }

   return response;
 }

流程
这里首先会获取到之前各个拦截器中的一些参数,首先会 httpCodec.writeRequestHeaders(request);通过这个httpCodec写入请求头信息,然后会写入请求的body信息,完成写入后会调用 httpCodec.finishRequest();
方法表示写入信息完成。

然后会读取响应信息,会先读取响应头信息,响应如果读取或者创建完成后会 通过streamAllocation.noNewStreams();这个方法进行关闭流,还会判断如果响应码是204或者205的话抛出一个异常。

其实这个拦截器链无非就是2个工作,发起请求,然后处理响应。至于中间会有一些封装请求信息判断响应信息等操作。

四、总结

这里拦截器的流程基本分析完了,其实主要还是看清大体流程和设计思路,具体细节的部分没有过多深入,因为这些流程设计模式才是真正要学习的重点。从源码看来 好多地方还是很值得学习的。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,839评论 6 482
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,543评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 153,116评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,371评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,384评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,111评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,416评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,053评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,558评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,007评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,117评论 1 334
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,756评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,324评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,315评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,539评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,578评论 2 355
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,877评论 2 345

推荐阅读更多精彩内容