OkHttp - Interceptors(一)

本文中源碼基于OkHttp 3.6.0

上一篇文章《OkHttp Request 請求執(zhí)行流程》中分析我們知道 OkHttp 的請求是一個鏈式的過程,在 RealCall 的 getResponseWithInterceptorChain() 方法中構建了一個請求處理鏈,鏈上的每一個節(jié)點都有相對獨立的功能,當它們完成自己的請求任務后就把處理結果返回給上一個節(jié)點,直到最后返回給發(fā)起請求的用戶。這些處理請求的節(jié)點就是 Interceptor,它們由下面幾種類型構成:

  1. 自定義 Interceptors ,由用戶自定義的 Interceptor,最早接收到 Request、最后完成對 Response 的處理;
  2. RetryAndFollowupInterceptor,負責處理鏈接失敗時的重試及重定向請求;
  3. BridgeInterceptor, 負責處理請求的 headers、cookie、gzip;
  4. CacheInterceptor,負責匹配請求的緩存、驗證緩存有效性、及保存響應的緩存;
  5. ConnectInterceptor,負責創(chuàng)建到服務器的鏈接;
  6. 自定義 Network Interceptors,同樣由用戶自定義,與之前的 Interceptor 最大的區(qū)別就是,請求執(zhí)行到這里已經與服務器建立上了連接;
  7. CallServerInterceptor,對服務器發(fā)起實際的請求,接收返回結果。

下面我們按照順序依次來分析各個系統(tǒng) Interceptor 對請求的處理。


- RetryAndFollowupInterceptor

RetryAndFollowupInterceptor 是第一個接收到 Request 的系統(tǒng) Interceptor ,它的主要作用是在后續(xù) Interceptor 處理請求遇到錯誤時,重新構造一個新的 Request 并再次發(fā)起請求,下面我們來看看它的 intercept 方法。

public Response intercept(Chain chain) throws IOException {
  Request request = chain.request();
  // 構建一個 StreamAllocation,其提供建立連接、管理復用連接的能力
  streamAllocation = new StreamAllocation(
      client.connectionPool(), createAddress(request.url()), callStackTrace);

  // 重定向次數計數器,默認超過20次就直接拋出錯誤
  int followUpCount = 0;
  Response priorResponse = null;
  while (true) {
    if (canceled) {
      streamAllocation.release();
      throw new IOException("Canceled");
    }

    Response response = null;
    boolean releaseConnection = true;
    try {
      // 交給下一個 Interceptor 處理請求
      response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
      releaseConnection = false;
    } catch (RouteException e) {
      // 連接失敗,判斷是否可以恢復連接,若不可恢復,直接拋出異常結束請求。此時還沒有發(fā)送請求
      if (!recover(e.getLastConnectException(), false, request)) {
        throw e.getLastConnectException();
      }
      releaseConnection = false;
      continue;
    } catch (IOException e) {
      // 在與服務器的通信過程中發(fā)生錯誤,判斷是否可以恢復連接,此時可能已經向服務器發(fā)送了請求
      boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
      if (!recover(e, requestSendStarted, request)) throw e;
      releaseConnection = false;
      continue;
    } finally {
      // 其他異常不處理,關閉連接釋放資源。
      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
    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;
  }
}

在將請求交由下一個節(jié)點處理之前,RetryAndFollowupInterceptor 創(chuàng)建了一個 StreamAllocation ,這個對象用來創(chuàng)建并維護客戶端到服務器的鏈接,在分析 ConnectInterceptor 的時候我們再來詳細地講解其功能實現。

在請求執(zhí)行的過程中,由于網絡等原因,可能會出現與服務器鏈接失敗、數據傳輸失敗等情況,為了盡量保證請求的可靠性,OkHttp 會自動對失敗的請求進行重試。這時通過 recover() 判斷客戶端是否可以恢復與服務器的連接,如果可以恢復,那么會使用 StreamAllocation 選擇另外一個 Route 重新創(chuàng)建一個連接;如果不能恢復則只能關閉連接,拋出異常。

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

  // 如果在 OkHttpClient 中設置了retryOnConnectionFailure,表示我們不允許進行請求重試
  if (!client.retryOnConnectionFailure()) return false;

  // 如果請求中包含不能重復提交的內容,則不允許重試
  if (requestSendStarted && userRequest.body() instanceof UnrepeatableRequestBody) return false;

  // 根據錯誤類型判斷是否能夠重試
  if (!isRecoverable(e, requestSendStarted)) return false;

  // 連接中并不存在下一個路由地址,則不能重試
  if (!streamAllocation.hasMoreRoutes()) return false;

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

在我們正常連接到服務器并發(fā)起請求的情況下,服務器返回的 Response 任然有可能不是我們需要的結果,比如發(fā)生服務器需要身份認證(401)、重定向(30x)的時候。那么下面我們再來看看 OkHttp 中對這一部分邏輯的處理。

private Request followUpRequest(Response userResponse) throws IOException {
  if (userResponse == null) throw new IllegalStateException();
  Connection connection = streamAllocation.connection();
  Route route = connection != null
      ? connection.route()
      : null;
  int responseCode = userResponse.code();

  final String method = userResponse.request().method();
  switch (responseCode) {
    // 407,代理認證,表示需要經過代理服務器的授權
    case HTTP_PROXY_AUTH:
      Proxy selectedProxy = route != null
          ? route.proxy()
          : client.proxy();
      if (selectedProxy.type() != Proxy.Type.HTTP) {
        throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");
      }
      // 交由 OkHttpClient 中設置的代理認證處理,默認未設置
      return client.proxyAuthenticator().authenticate(route, userResponse);

    // 401,基本認證,訪問被拒絕,需要授權
    case HTTP_UNAUTHORIZED:
      // 交由用戶設置的認證處理,默認未設置
      return client.authenticator().authenticate(route, userResponse);

    // 308,永久遷移
    case HTTP_PERM_REDIRECT:
    // 307,臨時遷移
    case HTTP_TEMP_REDIRECT:
      // 服務器為了禁止一味地使用重定向,將這幾個狀態(tài)碼區(qū)分開,如果該請求不是 GET 或者 HEAD,那么不進行自動重定向,交給用戶自己處理
      if (!method.equals("GET") && !method.equals("HEAD")) {
        return null;
      }
    // 300,請求的資源存在多個候選地址,同時返回一個選項列表
    case HTTP_MULT_CHOICE:
    // 301,資源被移動到新的位置
    case HTTP_MOVED_PERM:
    // 302,類似301
    case HTTP_MOVED_TEMP:
    // 303,類似301、302
    case HTTP_SEE_OTHER:
      // 如果設置禁止重定向,則返回 null
      if (!client.followRedirects()) return null;

      String location = userResponse.header("Location");
      if (location == null) return null;
      // 解析 Location 中地址
      HttpUrl url = userResponse.request().url().resolve(location);

      // Don't follow redirects to unsupported protocols.
      if (url == null) return null;

      // 這里判斷原始請求地址和重定向的地址是否使用相同協(xié)議(同為 Http 或 Https)
      boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
      // 判斷 OkHttp 中配置是否允許跨協(xié)議的重定向
      if (!sameScheme && !client.followSslRedirects()) return null;

      // Most redirects don't include a request body.
      Request.Builder requestBuilder = userResponse.request().newBuilder();
      // 這里處理重定向請求中的實體部分
      if (HttpMethod.permitsRequestBody(method)) {
        // 重定向中是否允許攜帶實體(PROPFIND方法允許攜帶實體,其他方法不允許攜帶實體,需要將請求改為 GET 請求)
        final boolean maintainBody = HttpMethod.redirectsWithBody(method);
        if (HttpMethod.redirectsToGet(method)) {
          requestBuilder.method("GET", null);
        } else {
          RequestBody requestBody = maintainBody ? userResponse.request().body() : null;
          requestBuilder.method(method, requestBody);
        }
        if (!maintainBody) {
          requestBuilder.removeHeader("Transfer-Encoding");
          requestBuilder.removeHeader("Content-Length");
          requestBuilder.removeHeader("Content-Type");
        }
      }

      // When redirecting across hosts, drop all authentication headers. This
      // is potentially annoying to the application layer since they have no
      // way to retain them.
      if (!sameConnection(userResponse, url)) {
        requestBuilder.removeHeader("Authorization");
      }
      // 使用重定向指定地址構建一個新的 request
      return requestBuilder.url(url).build();

    // 408,請求超時,不修改請求,直接重試
    case HTTP_CLIENT_TIMEOUT:
      // 408's are rare in practice, but some servers like HAProxy use this response code. The
      // spec says that we may repeat the request without modifications. Modern browsers also
      // repeat the request (even non-idempotent ones.)
      if (userResponse.request().body() instanceof UnrepeatableRequestBody) {
        return null;
      }

      return userResponse.request();

    default:
      return null;
  }
}

RetryAndFollowupInterceptor 在接收到來自服務器的 Response 后,通過 followUpRequest() 方法判斷是否需要對該請求進行重試,如果需要重試,則構建一個新的 Request 以便再次發(fā)起請求;如果拿到的 Response 就是最終的結果,就直接將 Response 返回給用戶,完成請求。

RetryAndFollowupInterceptor 的處理流程

- BridgeInterceptor

BridgeInterceptor 中的源碼理解起來相對比較簡單,在將請求交付給下一個處理節(jié)點前,它的主要作用是在 Request 的 Header 中添加缺失的頭部信息(Content-Type、本地存儲的 Cookie 信息),以及在接收到服務器返回的 Response 后存儲 Header 中的 Cookie,并解壓響應實體(如果是 gzip 的話)。

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) {
      // 設置 Content-Type(text、image、video 等)
      requestBuilder.header("Content-Type", contentType.toString());
    }

    // contentLength 用于標識實體實體大小,便于服務器判斷實體是否傳輸完畢。
    // 如果指定了 contentLength,則在 header 中添加;如果沒有指定,則使用 Transfer-Encoding: chunked 分塊編碼方式。
    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");
    }
  }

  // 設置 Host
  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");
  }

  // 獲取對應 url 下的 cookie
  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());
  }

  // 后續(xù) Interceptor 處理請求
  Response networkResponse = chain.proceed(requestBuilder.build());

  // 保持 Response 中的 cookie
  HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());

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

  // 如果請求中設置了 Content-Encoding: gzip,完成對 body 的解壓
  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();
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 這篇文章主要講 Android 網絡請求時所使用到的各個請求庫的關系,以及 OkHttp3 的介紹。(如理解有誤,...
    小莊bb閱讀 1,322評論 0 4
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現,斷路器,智...
    卡卡羅2017閱讀 136,506評論 19 139
  • 前言:對于OkHttp我接觸的時間其實不太長,一直都是使用Retrofit + OkHttp 來做網絡請求的,但是...
    mecury閱讀 41,465評論 23 178
  • http://www.cnblogs.com/wxisme/p/5196302.htmlvim config/se...
    558f565a3cd7閱讀 923評論 0 0
  • 已時至深秋,前幾日陰雨連連的天氣今終停了。天似乎放晴,卻也不是本該秋日里的天高云淡,即使這樣,也好過那鉛色的...
    傅清明閱讀 430評論 3 3

友情鏈接更多精彩內容