okhttp——RetryAndFollowUpInterceptor

簡(jiǎn)介

okhttp的網(wǎng)絡(luò)請(qǐng)求采用interceptors鏈的模式。每一級(jí)interceptor只處理自己的工作,然后將剩余的工作廉涕,交給下一級(jí)interceptor。本文將主要閱讀okhttp中的RetryAndFollowUpInterceptor艇拍,了解它的作用和工作原理狐蜕。

RetryAndFollowUpInterceptor

顧名思義,RetryAndFollowUpInterceptor負(fù)責(zé)okhttp的請(qǐng)求失敗的恢復(fù)和重定向卸夕。

核心的intercept方法分兩段閱讀:


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

    int followUpCount = 0;
    Response priorResponse = null;
    while (true) {
      transmitter.prepareToConnect(request);

      if (transmitter.isCanceled()) {
        throw new IOException("Canceled");
      }

      Response response;
      boolean success = false;
      try {
        response = realChain.proceed(request, transmitter, null);
        success = true;
      } catch (RouteException e) {
        // The attempt to connect via a route failed. The request will not have been sent.
        if (!recover(e.getLastConnectException(), transmitter, false, request)) {
          throw e.getFirstConnectException();
        }
        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, transmitter, requestSendStarted, request)) throw e;
        continue;
      } finally {
        // The network call threw an exception. Release any resources.
        if (!success) {
          transmitter.exchangeDoneDueToException();
        }
      }
      ...
    }
  }

前半段的邏輯中层释,RetryAndFollowUpInterceptor做了幾件事:

  • 通過(guò)Transmitter準(zhǔn)備連接
  • 執(zhí)行請(qǐng)求鏈下一級(jí)
  • 處理了下一級(jí)請(qǐng)求鏈中的RouteExceptionIOException

Transmitter的實(shí)現(xiàn)快集,以后的章節(jié)再單獨(dú)講解贡羔。此處略過(guò)。我們重點(diǎn)看一下个初,RetryAndFollowUpInterceptor如何處理兩個(gè)異常乖寒。

RouteException

從注釋中,我們可以看到勃黍,RouteException表示客戶端連接路由失敗宵统。此時(shí)會(huì)調(diào)用recover方法,如果recover方法再失敗覆获,會(huì)拋出RouteException中的FirstConnectException

我們看一下recover方法的實(shí)現(xiàn):

  /**
   * Report and attempt to recover from a failure to communicate with a server. Returns true if
   * {@code e} is recoverable, or false if the failure is permanent. Requests with a body can only
   * be recovered if the body is buffered or if the failure occurred before the request has been
   * sent.
   */
  private boolean recover(IOException e, Transmitter transmitter,
      boolean requestSendStarted, Request userRequest) {
    // The application layer has forbidden retries.
    if (!client.retryOnConnectionFailure()) return false;

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

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

    // No more routes to attempt.
    if (!transmitter.canRetry()) return false;

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

首先我們調(diào)用應(yīng)用層的失敗回調(diào)瓢省,如果應(yīng)用層返回false弄息,就不再進(jìn)行重試。

然后勤婚,我們判斷請(qǐng)求的返回摹量,如果請(qǐng)求已經(jīng)開(kāi)始或請(qǐng)求限定,只能請(qǐng)求一次,我們也不再進(jìn)行重試缨称。其中凝果,只能請(qǐng)求一次,可能是客戶端自行設(shè)定的睦尽,也可能是請(qǐng)求返回了404器净。明確告知了文件不存在,也不會(huì)再重復(fù)請(qǐng)求当凡。

接下來(lái)山害,是okhttp認(rèn)為的致命錯(cuò)誤,不會(huì)再重復(fù)請(qǐng)求的沿量,都會(huì)在isRecoverable方法中浪慌。致命錯(cuò)誤包括:協(xié)議錯(cuò)誤、SSL校驗(yàn)錯(cuò)誤等朴则。

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

最后权纤,在底層中尋找是否還有其他的Router可以嘗試。

IOException

IOException表示連接已經(jīng)建立乌妒,但讀取內(nèi)容時(shí)失敗了妖碉。我們同樣會(huì)進(jìn)行recover嘗試,由于代碼邏輯一樣芥被,不再重復(fù)閱讀欧宜。

在finally中,Transmitter會(huì)釋放所有資源拴魄。


followUpRequest

接下來(lái)冗茸,我們看一下RetryAndFollowUpInterceptorintercept后半段的實(shí)現(xiàn):

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

    int followUpCount = 0;
    Response priorResponse = null;
    while (true) {
     ...

      // 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();
      }

      Exchange exchange = Internal.instance.exchange(response);
      Route route = exchange != null ? exchange.connection().route() : null;
      Request followUp = followUpRequest(response, route);

      if (followUp == null) {
        if (exchange != null && exchange.isDuplex()) {
          transmitter.timeoutEarlyExit();
        }
        return response;
      }

      RequestBody followUpBody = followUp.body();
      if (followUpBody != null && followUpBody.isOneShot()) {
        return response;
      }

      closeQuietly(response.body());
      if (transmitter.hasExchange()) {
        exchange.detachWithViolence();
      }

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

      request = followUp;
      priorResponse = response;
    }
  }

我們拆開(kāi)來(lái)看這段復(fù)雜的邏輯。大體上來(lái)說(shuō)匹中,這段邏輯主要是通過(guò)上次請(qǐng)求的返回夏漱,生成followUp。然后根據(jù)followUp的內(nèi)容顶捷,判斷是不是有效的返回挂绰。如果返回是有效的,就直接return請(qǐng)求的返回服赎。如果返回?zé)o效葵蒂,則request=followUp,重走while循環(huán)重虑,重新請(qǐng)求践付。

所以這一段的核心邏輯在于followUpRequest方法。我們來(lái)看下followUpRequest的實(shí)現(xiàn)缺厉。

  /**
   * Figures out the HTTP request to make in response to receiving {@code userResponse}. This will
   * either add authentication headers, follow redirects or handle a client request timeout. If a
   * follow-up is either unnecessary or not applicable, this returns null.
   */
  private Request followUpRequest(Response userResponse, @Nullable Route route) throws IOException {
    if (userResponse == null) throw new IllegalStateException();
    int responseCode = userResponse.code();

    final String method = userResponse.request().method();
    switch (responseCode) {
      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");
        }
        return client.proxyAuthenticator().authenticate(route, userResponse);

      case HTTP_UNAUTHORIZED:
        return client.authenticator().authenticate(route, userResponse);

      case HTTP_PERM_REDIRECT:
      case HTTP_TEMP_REDIRECT:
        // "If the 307 or 308 status code is received in response to a request other than GET
        // or HEAD, the user agent MUST NOT automatically redirect the request"
        if (!method.equals("GET") && !method.equals("HEAD")) {
          return null;
        }
        // fall-through
      case HTTP_MULT_CHOICE:
      case HTTP_MOVED_PERM:
      case HTTP_MOVED_TEMP:
      case HTTP_SEE_OTHER:
        // Does the client allow redirects?
        if (!client.followRedirects()) return null;

        String location = userResponse.header("Location");
        if (location == null) return null;
        HttpUrl url = userResponse.request().url().resolve(location);

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

        // If configured, don't follow redirects between SSL and non-SSL.
        boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
        if (!sameScheme && !client.followSslRedirects()) return null;

        // Most redirects don't include a request body.
        Request.Builder requestBuilder = userResponse.request().newBuilder();
        if (HttpMethod.permitsRequestBody(method)) {
          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.request().url(), url)) {
          requestBuilder.removeHeader("Authorization");
        }

        return requestBuilder.url(url).build();

      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 (!client.retryOnConnectionFailure()) {
          // The application layer has directed us not to retry the request.
          return null;
        }

        RequestBody requestBody = userResponse.request().body();
        if (requestBody != null && requestBody.isOneShot()) {
          return null;
        }

        if (userResponse.priorResponse() != null
            && userResponse.priorResponse().code() == HTTP_CLIENT_TIMEOUT) {
          // We attempted to retry and got another timeout. Give up.
          return null;
        }

        if (retryAfter(userResponse, 0) > 0) {
          return null;
        }

        return userResponse.request();

      case HTTP_UNAVAILABLE:
        if (userResponse.priorResponse() != null
            && userResponse.priorResponse().code() == HTTP_UNAVAILABLE) {
          // We attempted to retry and got another timeout. Give up.
          return null;
        }

        if (retryAfter(userResponse, Integer.MAX_VALUE) == 0) {
          // specifically received an instruction to retry without delay
          return userResponse.request();
        }

        return null;

      default:
        return null;
    }
  }

這段代碼非常長(zhǎng)永高,大部分是switch/case的各種返回碼處理隧土。followUpRequest方法從宏觀上來(lái)講,是輸入response命爬,生成新的requests曹傀。如果response的內(nèi)容不需要重試,則直接返回null饲宛。如果需要重試皆愉,則根據(jù)response的內(nèi)容,生成重試策略落萎,返回重試發(fā)出的request亥啦。

其中,重定向和超時(shí)是最主要的重試情況练链。在處理重定向和超時(shí)時(shí)翔脱,okhttp進(jìn)行了很多判斷,排除了一些不必要重試的情況媒鼓。如届吁,location不存在,或者重定向的url協(xié)議頭不一致等情況绿鸣。

followUpCount則是為了限制okhttp的重試次數(shù)疚沐。


總結(jié)

RetryAndFollowUpInterceptorokhttp中承擔(dān)了重試和重定向的邏輯。其中包括了潮模,建立連接亮蛔、讀取內(nèi)容失敗的重試 和 完整讀取請(qǐng)求返回后的重定向。針對(duì)各種返回碼擎厢,okhttp對(duì)無(wú)需重試的一些場(chǎng)景進(jìn)行了裁剪究流,減少了無(wú)效重試的概率。同時(shí)动遭,對(duì)不規(guī)范的重定向返回進(jìn)行的過(guò)濾和校驗(yàn)芬探。

網(wǎng)絡(luò)請(qǐng)求的場(chǎng)景復(fù)雜,在設(shè)計(jì)網(wǎng)絡(luò)框架時(shí)厘惦,對(duì)于各種未知情況的處理偷仿,是一項(xiàng)比較有挑戰(zhàn)的工作。okhttp作為一個(gè)高可用的網(wǎng)絡(luò)框架宵蕉,在RetryAndFollowUpInterceptor這一攔截器中酝静,提供了一個(gè)異常處理的優(yōu)秀范本。

當(dāng)讀者需要自己設(shè)計(jì)網(wǎng)絡(luò)庫(kù)時(shí)国裳,可以參考okhttpRetryAndFollowUpInterceptor對(duì)于異常處理的做法形入,避免一些難以預(yù)測(cè)和重現(xiàn)的問(wèn)題。

如有問(wèn)題缝左,歡迎指正。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市渺杉,隨后出現(xiàn)的幾起案子蛇数,更是在濱河造成了極大的恐慌,老刑警劉巖是越,帶你破解...
    沈念sama閱讀 207,113評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件耳舅,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡倚评,警方通過(guò)查閱死者的電腦和手機(jī)浦徊,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,644評(píng)論 2 381
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)天梧,“玉大人盔性,你說(shuō)我怎么就攤上這事∧馗冢” “怎么了冕香?”我有些...
    開(kāi)封第一講書人閱讀 153,340評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)后豫。 經(jīng)常有香客問(wèn)我悉尾,道長(zhǎng),這世上最難降的妖魔是什么挫酿? 我笑而不...
    開(kāi)封第一講書人閱讀 55,449評(píng)論 1 279
  • 正文 為了忘掉前任构眯,我火速辦了婚禮,結(jié)果婚禮上早龟,老公的妹妹穿的比我還像新娘惫霸。我一直安慰自己,他們只是感情好拄衰,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,445評(píng)論 5 374
  • 文/花漫 我一把揭開(kāi)白布它褪。 她就那樣靜靜地躺著,像睡著了一般翘悉。 火紅的嫁衣襯著肌膚如雪茫打。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 49,166評(píng)論 1 284
  • 那天妖混,我揣著相機(jī)與錄音老赤,去河邊找鬼。 笑死制市,一個(gè)胖子當(dāng)著我的面吹牛抬旺,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播祥楣,決...
    沈念sama閱讀 38,442評(píng)論 3 401
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼开财,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼汉柒!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起责鳍,我...
    開(kāi)封第一講書人閱讀 37,105評(píng)論 0 261
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤碾褂,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后历葛,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體正塌,經(jīng)...
    沈念sama閱讀 43,601評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,066評(píng)論 2 325
  • 正文 我和宋清朗相戀三年恤溶,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了乓诽。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,161評(píng)論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡咒程,死狀恐怖鸠天,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情孵坚,我是刑警寧澤粮宛,帶...
    沈念sama閱讀 33,792評(píng)論 4 323
  • 正文 年R本政府宣布,位于F島的核電站卖宠,受9級(jí)特大地震影響巍杈,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜扛伍,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,351評(píng)論 3 307
  • 文/蒙蒙 一筷畦、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧刺洒,春花似錦鳖宾、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 30,352評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至因俐,卻和暖如春拇惋,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背抹剩。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 31,584評(píng)論 1 261
  • 我被黑心中介騙來(lái)泰國(guó)打工撑帖, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人澳眷。 一個(gè)月前我還...
    沈念sama閱讀 45,618評(píng)論 2 355
  • 正文 我出身青樓胡嘿,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親钳踊。 傳聞我的和親對(duì)象是個(gè)殘疾皇子衷敌,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,916評(píng)論 2 344

推薦閱讀更多精彩內(nèi)容