OkHttp-RetryAndFollowUpInterceptor源碼解析

RetryAndFollowUpInterceptor源碼分析

本文基於okhttp3.10.0

近段時間準備陸陸續續把okhttp攔截器分析一遍,既然是本系列開篇那先來回顧下攔截器是幹嘛的,然後在開始今天的主題。

1. 攔截器簡介

先簡單看下攔截器是幹嘛的,okhttp默認給我們提供了5個攔截器

  • RetryAndFollowUpInterceptor
  • BridgeInterceptor
  • CacheInterceptor
  • ConnectInterceptor
  • CallServerInterceptor

當我們通過okhttp發送請求的時候是將請求封裝爲一個Request對象,然後包裝成一個即將請求的Call對象,無論是異步或者同步請求最終都是通過RealCall#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));

    Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
        originalRequest, this, eventListener, client.connectTimeoutMillis(),
        client.readTimeoutMillis(), client.writeTimeoutMillis());

    return chain.proceed(originalRequest);
  }

可以看到是將攔截器組合起來創建一個RealInterceptorChain對象並將第五個參數賦值爲0,而第五個參數是賦值給了RealInterceptorChain中的index成員變量,然後通過chain#proceed(originalRequest)獲取請求結果。

  public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
      RealConnection connection) throws IOException {
    ...
    // Call the next interceptor in the chain.
    RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
        connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
        writeTimeout);//index+1鏈條的下一個節點
    Interceptor interceptor = interceptors.get(index);//拿到第一個攔截器
    Response response = interceptor.intercept(next);
    ...
    return response;
  }

第一次進來的時候index爲0所以拿到的是第一個攔截器,而interceptor#intercept()傳入的RealInterceptorChain的index爲index+1即爲1,所以當攔截器中調用chain#proceed(originalRequest)則會調到下個攔截器形成一個遞歸關係,完成整個攔截器鏈的調用。

//攔截器僞代碼
public class Interceptor {
  Response intercept(Chain chain) throws IOException{
    Request request = chain.request();
    //對Request做操作
    Response response = chain.process()
    //對Response做操作
  }
}

那麼可以簡單的理解攔截器就是處理請求的,輸入一個請求返回一個響應,按照http協議約定的代碼實現。

2. RetryAndFollowUpInterceptor做了啥

  1. 創建StreamAllocation它會在 ConnectInterceptor 中真正被使用到,主要就是用於獲取連接服務端的 Connection 和用於進行跟服務端進行數據傳輸的輸入輸出流 HttpStream,具體的操作後面用到再說
  2. 出錯重試
  3. 繼續請求(主要是重定向)

2.1 出錯重試

  @Override public Response intercept(Chain chain) throws IOException {
    while (true) {
      if (canceled) {//請求取消了釋放連接
        streamAllocation.release();
        throw new IOException("Canceled");
      }

      Response response;
      boolean releaseConnection = true;//默認釋放連接
      try {
        response = realChain.proceed(request, streamAllocation, null, null);
        releaseConnection = false;//請求成功暫不釋放連接
      } catch (RouteException e) {
        //出現異常判斷能不能進行重試
        if (!recover(e.getLastConnectException(), streamAllocation, false, request)) {
          throw e.getLastConnectException();
        }
        releaseConnection = false;//可以重試不釋放連接
        continue;//通過continue繼續執行while循環重試
      } catch (IOException e) {
        //出現異常判斷能不能進行重試
        boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
        if (!recover(e, streamAllocation, requestSendStarted, request)) throw e;
        releaseConnection = false;//可以重試不釋放連接
        continue;//通過continue繼續執行while循環重試
      } finally {
        //不能重試則釋放資源
        if (releaseConnection) {
          streamAllocation.streamFailed(null);
          streamAllocation.release();
        }
      }
    }
  }

請求取消了釋放連接,請求成功暫不釋放連接,請求拋出RouteException和IOException通過recover()判斷能不能進行重試,如果可以也暫不釋放連接,並通過continue繼續進行while循環重新請求。

  private boolean recover(IOException e, StreamAllocation streamAllocation,
      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;//如果請求已經發送並且body實現了UnrepeatableRequestBody則不重試

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

第一個if是調用client#retryOnConnectionFailure()判斷能不能進行重試

  public boolean retryOnConnectionFailure() {
    return retryOnConnectionFailure;
  }

而它實際是讀取的OkHttpClient的retryOnConnectionFailure屬性默認爲true支持重試

第二個if是判斷如果請求已經發送,並且body實現了UnrepeatableRequestBody則不再重試,UnrepeatableRequestBody在這裏只是做一個標記的作用

第三個if判斷是不是致命異常,如果是則不再重試

  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) {//ssl握手異常
      // 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;
  }

第四個if如果沒有更多的線路則不進行重試,其他情況則進行重試

2.2 繼續請求(主要是重定向)

  @Override public Response intercept(Chain chain) throws IOException {
    int followUpCount = 0;//繼續請求次數
    Response priorResponse = null;//上次的響應
    while (true) {
      //...省略請求重試代碼

      // Attach the prior response if it exists. Such responses never have a body.
      if (priorResponse != null) {//如果有前一個響應則附加到responses中
        response = response.newBuilder()
            .priorResponse(priorResponse.newBuilder()
                    .body(null)
                    .build())
            .build();
      }

      Request followUp = followUpRequest(response, streamAllocation.route());//判斷需不需要繼續請求

      if (followUp == null) {//不需要繼續請求
        if (!forWebSocket) {
          streamAllocation.release();
        }
        return response;//直接返回響應
      }
			//下面則是需要繼續請求
      closeQuietly(response.body());//去掉body

      if (++followUpCount > MAX_FOLLOW_UPS) {//如果繼續請求次數大於20次報錯終止
        streamAllocation.release();
        throw new ProtocolException("Too many follow-up requests: " + followUpCount);
      }

      if (followUp.body() instanceof UnrepeatableRequestBody) {//如果body實現了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);
        this.streamAllocation = streamAllocation;
      } else if (streamAllocation.codec() != null) {
        throw new IllegalStateException("Closing the body of " + response
            + " didn't close its backing stream. Bad interceptor?");
      }

      request = followUp;//記錄繼續請求的request
      priorResponse = response;//上次的response
    }
  }

代碼註釋已經很全了,直接看到對於繼續請求的判斷followUpRequest()

  private Request followUpRequest(Response userResponse, Route route) throws IOException {
    if (userResponse == null) throw new IllegalStateException();
    int responseCode = userResponse.code();//拿到http狀態碼

    final String method = userResponse.request().method();//請求方法
    switch (responseCode) {
      case HTTP_PROXY_AUTH://407代理服務器驗證
        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);//返回一個附帶驗證信息的Request
      case HTTP_UNAUTHORIZED://401407類似,只不過401是服務器驗證失敗
        return client.authenticator().authenticate(route, userResponse);//返回一個附帶驗證信息的Request

      case HTTP_PERM_REDIRECT://308
      case HTTP_TEMP_REDIRECT://307
        // "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")) {//307 308如果不是get或者head的話則不在進行重定向
          return null;
        }
        // fall-through
      case HTTP_MULT_CHOICE://300
      case HTTP_MOVED_PERM://301
      case HTTP_MOVED_TEMP://302
      case HTTP_SEE_OTHER://303
        // 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);//解析成HttpUrl對象

        // 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;//是否允許http到https重定向

        // Most redirects don't include a request body.
        Request.Builder requestBuilder = userResponse.request().newBuilder();
        if (HttpMethod.permitsRequestBody(method)) {//如果請求方法不是get或者head
          final boolean maintainBody = HttpMethod.redirectsWithBody(method);//請求方法爲PROPFIND需要有body
          if (HttpMethod.redirectsToGet(method)) {//如果請求方法不是PROPFIND重定向爲get請求並去除請求體
            requestBuilder.method("GET", null);
          } else {//請求方法是PROPFIND,加入請求體並保持原有請求方法
            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)) {//不是同一個連接移除Authorization字段
          requestBuilder.removeHeader("Authorization");
        }

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

      case HTTP_CLIENT_TIMEOUT://408 進行重試
        // 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;
        }

        if (userResponse.request().body() instanceof UnrepeatableRequestBody) {
          return null;
        }

        if (userResponse.priorResponse() != null
            && userResponse.priorResponse().code() == HTTP_CLIENT_TIMEOUT) {//發生兩次408則不在重試
          // We attempted to retry and got another timeout. Give up.
          return null;
        }

        if (retryAfter(userResponse, 0) > 0) {//response中Retry-After有值則不再重試
          return null;
        }

        return userResponse.request();

      case HTTP_UNAVAILABLE://503 默認不重試
        if (userResponse.priorResponse() != null
            && userResponse.priorResponse().code() == HTTP_UNAVAILABLE) {//出現兩次503則不再重試
          // We attempted to retry and got another timeout. Give up.
          return null;
        }

        if (retryAfter(userResponse, Integer.MAX_VALUE) == 0) {//response中包含Retry-After並且值爲0進行重試
          // specifically received an instruction to retry without delay
          return userResponse.request();
        }

        return null;

      default:
        return null;
    }
  }

這裏就是對http響應碼做區分看是否需要再次請求,先來科普下http響應碼

  • 401 & 407 身份驗證
  • 300 & 301 & 302 & 304 & 307 & 308 重定向
  • 408 客戶端超時不常用
  • 503 服務器不可用

返回碼爲401&407的話,獲取帶驗證信息的Request重新請求,408這個不常用默認是會重試的,503爲服務不可用默認不重試,接下來是重頭戲3xx重定向。

      case HTTP_PERM_REDIRECT://308
      case HTTP_TEMP_REDIRECT://307
        if (!method.equals("GET") && !method.equals("HEAD")) {//307 308如果不是get或者head的話則不在進行重定向
          return null;
        }
      case HTTP_MULT_CHOICE://300
      case HTTP_MOVED_PERM://301
      case HTTP_MOVED_TEMP://302
      case HTTP_SEE_OTHER://303
        if (!client.followRedirects()) return null;//客戶端是否允許重定向 默認是允許

        String location = userResponse.header("Location");//獲取響應頭中重定向地址
        if (location == null) return null;
        HttpUrl url = userResponse.request().url().resolve(location);//解析成HttpUrl對象

        if (url == null) return null;

        boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
        if (!sameScheme && !client.followSslRedirects()) return null;//是否允許http到https重定向

        Request.Builder requestBuilder = userResponse.request().newBuilder();
        if (HttpMethod.permitsRequestBody(method)) {//如果請求方法不是get或者head
          final boolean maintainBody = HttpMethod.redirectsWithBody(method);//請求方法爲PROPFIND需要有body
          if (HttpMethod.redirectsToGet(method)) {//如果請求方法不是PROPFIND重定向爲get請求並去除請求體
            requestBuilder.method("GET", null);
          } else {//請求方法是PROPFIND,加入請求體並保持原有請求方法
            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");
          }
        }

        if (!sameConnection(userResponse, url)) {//不是同一個連接移除Authorization字段
          requestBuilder.removeHeader("Authorization");
        }

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

可以看到在返回碼307或308的時候,只有請求方法不是get不是head纔會重定向,300、301、302、303都會重定向,先判斷客戶端是否允許重定向client#followRedirects(),默認是允許的,然後拿到response中頭部location的值作爲重定向地址,然後對url做了一些判斷,最關鍵的來了如果你的請求不是get不是head,我們就假設是post則他會重定向爲get請求並且把請求體丟了,對你沒有看錯基本等於是重定向一律轉爲get請求並且把請求體丟了。 其實http協議中規定的是301、302禁止將post轉爲get的,但是由於大部分瀏覽器都沒有遵守都是轉爲了get,所以okhttp也沿用了這個做法。

3. 總結

簡單總結下RetryAndFollowUpInterceptor做了3件大事

  1. 創建StreamAllocation(這個後面細說)
  2. 請求發生錯誤,判斷能不能恢復,如果可以進行重試
  3. 根據響應碼進行區分處理,我們最常用的重定向就是在這裏處理,需要注意的是重定向一律轉爲get請求並丟棄了請求體
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章