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

作者: 开飞机的老舒克 | 来源:发表于2018-01-12 18:11 被阅读70次

    一、拦截器链流程图

    连接器练流程图

    二、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个工作,发起请求,然后处理响应。至于中间会有一些封装请求信息判断响应信息等操作。

    四、总结

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

    相关文章

      网友评论

        本文标题:OkHttp中的拦截器机制源码解析

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