天天看點

okhttp3源碼分析之RetryAndFollowUpInterceptor

功能:重試與重定向攔截器。

由于是工廠方法模式,直接調用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);
	  ...
      Response response;
      boolean success = false;
      try {
      	//交給下一個攔截起處理
        response = realChain.proceed(request, transmitter, null);
        success = true;
      } catch (RouteException e) {
        ...
        continue;
      }...

      ...
	  //根據異常狀态,傳回request對象(判斷網絡狀态404...)
      Request followUp = followUpRequest(response, route);
	  //如果為null(沒有異常)關閉請求
      if (followUp == null) {
        ...
        return response;
      }
	  //如果body不是空,并且設定了最多可以傳輸一次,傳回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;
    }
  }
           
okhttp3源碼分析之RetryAndFollowUpInterceptor

特點:

  1. 通過while(true)死循環來進行重新連接配接
  2. 通過響應碼來決定下一次循環的行為是重試、重定向。。。

繼續閱讀