OkHttp之攔截器(二)

本篇文章主要介紹OkHttp的默認攔截器

  • 重試攔截器
  • 橋接攔截器
  • 緩存攔截器
  • 連接攔截器
  • 訪問服務器攔截器

通過攔截器將OkHttp的訪問網絡的過程進行分解,每個攔截器專司其職. 所有的攔截器都實現了Interceptor接口

public interface Interceptor {
  Response intercept(Chain chain) throws IOException;

  interface Chain {
    Request request();

    Response proceed(Request request) throws IOException;

    Connection connection();
  }
}

好了,下面我們看看這些攔截器都做了什么,由上面的接口我們只用關心 Response proceed(Request request) throws IOException方法

一,重試攔截器RetryAndFollowUpInterceptor

@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 {
        response = ((RealInterceptorChain) chain).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;
        Log.i("xxx","retry  "+e.toString() );
        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;
        Log.i("xxx","retry io "+e.toString() );
        continue;
      } finally {
        Log.i("xxx","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()), 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;
    }
  }

1,和Volley的重試機制類似, 首先開啟一個死循環while(true)
當沒有獲取到響應且出現的異常是可以重試的, 他將一直重試

2,接下來會判斷是否取消,如果取消,則直接拋出異常,然后在AsyncCall的execute方法中直接回調失敗的方法 responseCallback.onFailure(RealCall.this, e);

3,通過response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
遞歸調用下一個攔截器獲取response
如果出現異常則通過recover函數判斷是否可以繼續重試
否則繼續向下執行.
下面看下recover函數, 里面列舉了四種況下是不能重試

private boolean recover(IOException e, boolean requestSendStarted, Request userRequest) {
    streamAllocation.streamFailed(e);

    // The application layer has forbidden retries.
    if (!client.retryOnConnectionFailure()) return false;

    // We can't send the request body again.
    if (requestSendStarted && userRequest.body() instanceof UnrepeatableRequestBody) return false;

    // This exception is fatal.
    if (!isRecoverable(e, requestSendStarted)) return false;

    // No more routes to attempt.
    if (!streamAllocation.hasMoreRoutes()) return false;

    // For failure recovery, use the same route selector with a new connection.
    return true;
  }

A,設置了禁止重試
B,重復發送請求體
C,出現了一些嚴重的錯誤,不能進一步重試
這些嚴重的錯誤在isRecoverable方法中的if判斷中提現
例如,協議錯誤,中斷,連接超時,SSL握手錯誤等等

private boolean isRecoverable(IOException e, boolean requestSendStarted) {
    // If there was a protocol problem, don't recover.
    if (e instanceof ProtocolException) {
      return false;
    }

    // If there was an interruption don't recover, but if there was a timeout connecting to a route
    // we should try the next route (if there is one).
    if (e instanceof InterruptedIOException) {
      return e instanceof SocketTimeoutException && !requestSendStarted;
    }

    // Look for known client-side or negotiation errors that are unlikely to be fixed by trying
    // again with a different route.
    if (e instanceof SSLHandshakeException) {
      // If the problem was a CertificateException from the X509TrustManager,
      // do not retry.
      if (e.getCause() instanceof CertificateException) {
        return false;
      }
    }
    if (e instanceof SSLPeerUnverifiedException) {
      // e.g. a certificate pinning error.
      return false;
    }

    // An example of one we might want to retry with a different route is a problem connecting to a
    // proxy and would manifest as a standard IOException. Unless it is one we know we should not
    // retry, we return true and try a new route.
    return true;
  }

D,沒有更多的路由線路來嘗試

4,當順利的得到Response響應以后,會通過 Request followUp = followUpRequest(response);來判斷是否存在重定向

  • 如果存在,則通過新的followUp來進行再次訪問,本次得到的響應存放在priorResponse中,然后繼續在這個死循環While(true)中再次發出請求. 對于這個重定向處理,Volley中默認是沒有的

  • 如果不存在,followUp那么為空,直接返回Response對象到上一個攔截器

二,橋接攔截器 BridgeInterceptor

橋接攔截器BridgeInterceptor比較簡單,主要干兩件事兒

  • 在遞歸調用下一個攔截器獲取Response后,構造Request的請求頭
  • 在得到響應Reponse后,構造Response的響應頭
 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", "sss");
//      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);
      responseBuilder.body(new RealResponseBody(strippedHeaders, Okio.buffer(responseBody)));
    }

    return responseBuilder.build();
  }

上面在構造請求頭的時候,值得注意的是,Content-Encoding和Content-Length不能同時出現.

  • Content-Length如果存在并且有效的話,則必須和消息內容的傳輸長度完全一致。如果過短則會截斷,過長則會導致超時。
  • HTTP1.1必須支持chunk模式。因為當不確定消息長度的時候,可以通過chunk機制來處理這種情況,也就是分塊傳輸。

三,緩存攔截器 CacheInterceptor

如果想比較好的理解緩存攔截器, 要對Http緩存機制有所了解, 特別是涉及到的請求和響應的請求頭
包括控制緩存時間的 Cache-Control , Expires
以及緩存服務器再驗證的 If-Modify-Since, If-None-Match
和緩存新鮮度的,no-cache, no-store, max-age , if-only-cache等
可以參考這篇文章

下面先貼出核心代碼

@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 (HttpHeaders.hasBody(response)) {
      CacheRequest cacheRequest = maybeCache(response, networkResponse.request(), cache);
      response = cacheWritingResponse(cacheRequest, response);
    }

    return response;
  }

1,首先根據Request的url從緩存中獲取緩存cacheCandidate
2,根據請求Request和從緩存中獲取的cacheCandidate(可能為空)來構造緩存策略CacheStrategy,下面看下是怎么構造的
A,首先構造Factory對象

 public Factory(long nowMillis, Request request, Response cacheResponse) {
    ... ...
        Headers headers = cacheResponse.headers();
        for (int i = 0, size = headers.size(); i < size; i++) {
          String fieldName = headers.name(i);
          String value = headers.value(i);
          if ("Date".equalsIgnoreCase(fieldName)) {
            servedDate = HttpDate.parse(value);
            servedDateString = value;
          } else if ("Expires".equalsIgnoreCase(fieldName)) {
            expires = HttpDate.parse(value);
          } else if ("Last-Modified".equalsIgnoreCase(fieldName)) {
            lastModified = HttpDate.parse(value);
            lastModifiedString = value;
          } else if ("ETag".equalsIgnoreCase(fieldName)) {
            etag = value;
          } else if ("Age".equalsIgnoreCase(fieldName)) {
            ageSeconds = HttpHeaders.parseSeconds(value, -1);
          }
        }
      }
    }

當后去的緩存響應不為空時,主要獲取這個響應的頭信息
Date, Expires Last-Modified ETag等信息,這些字段是用來判斷緩存是否過期,以及緩存驗證的

B,接下來獲取緩存策略

public CacheStrategy get() {
      CacheStrategy candidate = getCandidate();

      if (candidate.networkRequest != null && request.cacheControl().onlyIfCached()) {
        // We're forbidden from using the network and the cache is insufficient.
        return new CacheStrategy(null, null);
      }

      return candidate;
    }


private CacheStrategy getCandidate() {
      if (cacheResponse == null) {
        return new CacheStrategy(request, null);
      }

      if (request.isHttps() && cacheResponse.handshake() == null) {
        return new CacheStrategy(request, null);
      }
... ....
  
      String conditionName;
      String conditionValue;
      if (etag != null) {
        conditionName = "If-None-Match";
        conditionValue = etag;
      } else if (lastModified != null) {
        conditionName = "If-Modified-Since";
        conditionValue = lastModifiedString;
      } else if (servedDate != null) {
        conditionName = "If-Modified-Since";
        conditionValue = servedDateString;
      } else {
        return new CacheStrategy(request, null); // No condition! Make a regular request.
      }

      Headers.Builder conditionalRequestHeaders = request.headers().newBuilder();
      Internal.instance.addLenient(conditionalRequestHeaders, conditionName, conditionValue);

      Request conditionalRequest = request.newBuilder()
          .headers(conditionalRequestHeaders.build())
          .build();
      return new CacheStrategy(conditionalRequest, cacheResponse);
    }

getCandidate是獲取緩存策略的核心
主要兩部分內容
1)不使用緩存,直接return new CacheStrategy(request, null);
2)使用緩存

  • 緩存不過期,直接返回Response
  • 緩存過期,使用If-None-Match與ETag或者If-Modified-Since與Last-Modify對緩存進行驗證.

3,我們再將目光回到CacheInterceptor的intercept方法
得到緩存策略CacheStrategy后
進行一系列判斷
1)如果CacheStrategy中的networkResponse和cacheResponse為空,說明Cache-Conrol是only-if-cache,則使用緩存
2)如果networkResponse為空,則說明緩存有效,則直接返回cacheResponse
3)如果緩存無效或者需要驗證,則調用下一個攔截器直接從網絡獲取. 在從網絡得到響應后,會有兩種情況需要處理

  • 200 ok 代表著從網絡獲取到新的響應 (要么是緩存過期獲取新內容,要么是緩存不存在從網絡獲取)
  • 304 Not Modify 代表 緩存過期,然后請求網絡進行驗證,但是內容為改變,這時用新的響應頭(Date Expires Cache-Control等)更新舊的緩存響應頭,然后將響應返回

至此,緩存攔截器分析完
對于緩存攔截器里面很多的if判斷, 這都是根據Http緩存機制來實現的.如果想要清晰的了解緩存攔截器,務必先看Http緩存機制
推薦的讀物:
英文比較好的話: RFC2616
<<Http權威指南>>第七章
快速了解的話可以參考tp緩存的介紹

四,連接攔截器 ConnectInterceptor

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容