美文网首页
okhttp3.6.0源码分析2——拦截器

okhttp3.6.0源码分析2——拦截器

作者: hello_小丁同学 | 来源:发表于2017-11-07 21:24 被阅读39次

okhttp3.6.0源码分析系列文章整体内容如下:

一 okhttp默认的拦截器

okhttp默认执行的拦截器有五个:

  1. RetryAndFollowUpInterceptor 重定向拦截器
  2. BridgeInterceptor 该拦截器是链接客户端代码和网络代码的桥梁,它首先将客户端构建的Request对象信息构建成真正的网络请求;然后发起网络请求,最后是将服务器返回的消息封装成一个Response对象。
  3. CacheInterceptor 缓存拦截器
  4. ConnectInterceptor 打开与服务器的连接
  5. CallServerInterceptor 开启与服务器的网络请求

1.1 拦截器调用

不管是同步请求还是异步请求都会调用

Response response = getResponseWithInterceptorChain();

来获取网络请求内容,下面来看下getResponseWithInterceptorChain()里面是如何实现的:

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));
    //将拦截器封装成InterceptorChain,注意 时候 index为0
    Interceptor.Chain chain = new RealInterceptorChain(
        interceptors, null, null, null, 0, originalRequest);
    return chain.proceed(originalRequest);
  }

从getResponseWithInterceptorChain方法返回时调用的chain.proceed(originalRequest)开始分析,该方法调用RealInterceptorChain的procees方法:

public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
      RealConnection connection) throws IOException {

    calls++;
    // Call the next interceptor in the chain.
    RealInterceptorChain next = new RealInterceptorChain(
        interceptors, streamAllocation, httpCodec, connection, index + 1, request); //构造一个RealInterceptorChain,新的RealInterceptorChain的index为1
    Interceptor interceptor = interceptors.get(index); //传入的index为0,所以为调用第一个拦截器,假如没有没有添加自定义的拦截器,interceptor是RetryAndFollowUpInterceptor
    Response response = interceptor.intercept(next); //调用的是RetryAndFollowUpInterceptor里的intercept方法
    return response;
  }

RetryAndFollowUpInterceptor中intercept方法:

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

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

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

      Response response = null;
      boolean releaseConnection = true;
      try {
       // 再次调用 RealInterceptorChain的proceed方法,注意这里streamAllocation不为null
        response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
      priorResponse = response;
    }
  }

再次进入RealInterceptorChain的proceed方法:

public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
      RealConnection connection) throws IOException {

    calls++;
    // Call the next interceptor in the chain.
    RealInterceptorChain next = new RealInterceptorChain(
        interceptors, streamAllocation, httpCodec, connection, index + 1, request); //构造一个RealInterceptorChain,新的RealInterceptorChain的index为2
    Interceptor interceptor = interceptors.get(index); //传入的index为1,所以为调用第二个拦截器,假如没有没有添加自定义的拦截器,interceptor是BridgeInterceptor 
    Response response = interceptor.intercept(next); //调用的是BridgeInterceptor 里的intercept方法
    return response;
  }

进入BridgeInterceptor 里的intercept方法:

@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());
    }
     //到这里为止又会进行新的回调,会再次进入RealInterceptorChain方法中去
    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);
      responseBuilder.body(new RealResponseBody(strippedHeaders, Okio.buffer(responseBody)));
    }

    return responseBuilder.build();
  }

BridgeInterceptor 中的 chain.proceed(requestBuilder.build());放在intercept方法request信息组装成功之后,这样等到请求结束,就可以在拿到response之后对响应内容进行处理了,这种实现方式太优雅了。
在运行proceed方法时又会跳转到RealInterceptorChain的procees方法:

public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
      RealConnection connection) throws IOException {

    calls++;
    // Call the next interceptor in the chain.
    RealInterceptorChain next = new RealInterceptorChain(
        interceptors, streamAllocation, httpCodec, connection, index + 1, request); //构造一个RealInterceptorChain,新的RealInterceptorChain的index为3
    Interceptor interceptor = interceptors.get(index); //传入的index为2,所以为调用第三个拦截器,假如没有没有添加自定义的拦截器,interceptor是CacheInterceptor
    Response response = interceptor.intercept(next); //调用的是CacheInterceptor里的intercept方法
    return response;
  }

CacheInterceptor里的intercept方法:

@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;
  }

networkResponse = chain.proceed(networkRequest);
proceed方法之前的部分是若是配置了缓存策略,并且有缓存,则直接取出,不再进行网络请求,链式调用也终止。
proceed方法执行之后的部分会根据缓存策略,对网络相应内容进行存储。
在调用chain.proceed时,再次进入RealInterceptorChain的proceed方法:

public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
      RealConnection connection) throws IOException {

    calls++;
    // Call the next interceptor in the chain.
    RealInterceptorChain next = new RealInterceptorChain(
        interceptors, streamAllocation, httpCodec, connection, index + 1, request); //构造一个RealInterceptorChain,新的RealInterceptorChain的index为4
    Interceptor interceptor = interceptors.get(index); //传入的index为3,所以为调用第四个拦截器,假如没有没有添加自定义的拦截器,interceptor是ConnectInterceptor 
    Response response = interceptor.intercept(next); //调用的是ConnectInterceptor 里的intercept方法
    return response;
  }

ConnectInterceptor 里的intercept方法:

@Override public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Request request = realChain.request();
   //获取在RetryAndFollowUpInterceptor中构建的streamAllocation
    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 httpCodec = streamAllocation.newStream(client, doExtensiveHealthChecks);
    //构建RealConnection 对象
    RealConnection connection = streamAllocation.connection();

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

ConnectInterceptor 里的intercept方法比较少,主要是为下一步网络请求做准备;
方法结束时调用realChain.proceed再次进入RealInterceptorChain的proceed方法:

public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
      RealConnection connection) throws IOException {

    calls++;
    // Call the next interceptor in the chain.
    RealInterceptorChain next = new RealInterceptorChain(
        interceptors, streamAllocation, httpCodec, connection, index + 1, request); //构造一个RealInterceptorChain,新的RealInterceptorChain的index为5
    Interceptor interceptor = interceptors.get(index); //传入的index为4,所以为调用第五个拦截器,假如没有没有添加自定义的拦截器,interceptor是CallServerInterceptor,这也是最后一个拦截器
    Response response = interceptor.intercept(next); //调用的是ConnectInterceptor 里的intercept方法
    return response;
  }
 @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();
    httpCodec.writeRequestHeaders(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();
        responseBuilder = httpCodec.readResponseHeaders(true);
      }

      if (responseBuilder == null) {
        // Write the request body if the "Expect: 100-continue" expectation was met.
        Sink requestBodyOut = httpCodec.createRequestBody(request, request.body().contentLength());
        BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
        request.body().writeTo(bufferedRequestBody);
        bufferedRequestBody.close();
      } 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) {
      responseBuilder = httpCodec.readResponseHeaders(false);
    }

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

    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;
  }

将请求报文通过socket传到服务端,读取响应报文,然后返回,终止链式调用。一层一层返回。

二 用户自定义拦截器

除了okhttp自定义的拦截器之外,用户也可以给自定义拦截器。
自定义的拦截器分为两种:

  1. 应用层拦截器,使用场景是:
  • Don't need to worry about intermediate responses like redirects and retries.
  • Are always invoked once, even if the HTTP response is served from the cache.
  • Observe the application's original intent. Unconcerned with OkHttp-injected headers like If-None-Match.
  • Permitted to short-circuit and not call Chain.proceed().
  • Permitted to retry and make multiple calls to Chain.proceed().
  1. 网络层拦截器,使用场景是:
  • Able to operate on intermediate responses like redirects and retries.
  • Not invoked for cached responses that short-circuit the network.
  • Observe the data just as it will be transmitted over the network.
  • Access to the Connection that carries the request.

拦截器添加的源码如下:

  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);
    return chain.proceed(originalRequest);
  }

拦截器执行流程如下所示:


拦截器执行流程

上面的这些使用场景结合源码看就很容易理解了。

2.1 应用层拦截器

client.interceptors获取的拦截器就是应用层的拦截器,会在所有拦截器之前处理request,这时候的request是没有被系统拦截器修改过的。
如果要拦截网络异常并上报,那么应该使用这类拦截器。

2.2 网络层拦截器

client.networkInterceptions()返回的是网络层拦截器,可以看出它拿到的request可能会被重定向,而且如果开启了网络缓存,那么是这类拦截器将不会被调用。因为他是最后被调用的,所以它能拿到最终被传输的请求,也是我们最后能够处理请求的机会。
facebook的stetho定义的拦截器StethoInterceptor就是一种网络层连接器:

new OkHttpClient.Builder()
    .addNetworkInterceptor(new StethoInterceptor())
    .build();

(完)

相关文章

网友评论

      本文标题:okhttp3.6.0源码分析2——拦截器

      本文链接:https://www.haomeiwen.com/subject/qpfsmxtx.html