吊打面試官——史上最詳細【OkHttp】 三

簡介:大三學生黨一枚!主攻Android開發,對於Web和後端均有了解。
個人語錄取乎其上,得乎其中,取乎其中,得乎其下,以頂級態度寫好一篇的博客。

前面已經簡單的介紹了攔截器的概念和每一種攔截器的作用,憑藉這一點還不足以打動面試官,還需要對每一個攔截器的源碼有所瞭解,才能夠扛住面試官的各種問題!

在這裏插入圖片描述

@TOC

1.RetryAndFollowUpInterceptor

1.1 源碼分析

我們知道攔截器鏈執行procced方法執行攔截器鏈中的每一個攔截器,攔截器則調用自身的intercept方法執行,所以我們只需要對intercept進行分析就可以了。

@Override 
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();//從攔截器鏈獲得原始的request請求,請求信息包含了url,攜帶的請求體等,如果需要重定向,可能會對Request做修改更新
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Call call = realChain.call();//獲得call請求的原始對象,下面會用到
    EventListener eventListener = realChain.eventListener();
    //創建StreamAllocation對象,他主要負責分配stream,這個對象在這裏創建,卻沒有被使用
    //他在後面的攔截會被使用,很重要
    StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
        createAddress(request.url()), call, eventListener, callStackTrace);
	
    this.streamAllocation = streamAllocation;

    int followUpCount = 0;//重試次數,默認最大重試次數是20
    Response priorResponse = null;//這個priorResponse記錄之前一次請求返回的Response
    while (true) {
      if (canceled) {
	  	//如果已經取消該請求,立即釋放streamAllocation,結束該請求,後面的攔截器都不會執行了
        streamAllocation.release();
        throw new IOException("Canceled");
      }

      Response response;//這個Resonse記錄每次請求返回的response,
      //就是根據response的返回結果判斷是否需要重試的
      boolean releaseConnection = true;//是否要釋放connection的標誌位
      try {
        response = realChain.proceed(request, streamAllocation, null, null);//調用下一個攔截器獲得Response
        releaseConnection = false;
      } catch (RouteException e) {
	  	//如果捕捉到路由異常
        // The attempt to connect via a route failed. The request will not have been sent.
        if (!recover(e.getLastConnectException(), streamAllocation, false, request)) {
          throw e.getFirstConnectException();
        }
        releaseConnection = false;
        continue;//嘗試重新請求
      } catch (IOException e) {
	  	//捕捉到IO異常
        // An attempt to communicate with a server failed. The request may have been sent.
        boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
        if (!recover(e, streamAllocation, requestSendStarted, request)) throw e;
        releaseConnection = false;
        continue;//嘗試重新請求
      } 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.
      //不保存響應體,所以body爲null
      if (priorResponse != null) {
	  	//保存最新的Response,第一次執行請求這個if判斷不會被執行
        response = response.newBuilder()
            .priorResponse(priorResponse.newBuilder()
                    .body(null)
                    .build())
            .build();
      }

      Request followUp;//如果followUp爲空表示沒必要進行重試,直接返回response
      try {
      //followUpRequest是判斷有沒有必要進行重試的方法,他需要根據response進行判斷得到followUp
        followUp = followUpRequest(response, streamAllocation.route());
      } catch (IOException e) {
        streamAllocation.release();
        throw e;
      }

      if (followUp == null) {
      //如果followUp爲空表示沒必要進行重試,直接返回response
        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())) {
	  	//比較是否是同一個host,port,schema
        streamAllocation.release();//如果不是,先釋放原來建立好的連接
        streamAllocation = new StreamAllocation(client.connectionPool(),
            createAddress(followUp.url()), call, eventListener, callStackTrace);
            //獲取最新followUp請求中指定的url建立流
        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;//將請求改爲重定向最新的請求
      priorResponse = response;//記錄最新的Response
    }
  }

1.2 工作原理

這些分析需要看懂才能明白RetryAndFollowUpInterceptor攔截器的工作原理!

看完源代碼以後,我們來簡單梳理一下RetryAndFollowUpInterceptor的工作原理。

原理:當RetryAndFollowUpInterceptor攔截器指定intercept方法時,第一次執行時,會調用後面的攔截器鏈獲得返回的Response,然後根據Response中的信息,最主要的就是狀態碼,重試次數,請求體是否允許重複請求,決定是否需要進行重新連接,既然要進行重新請求,那麼有可能會對url進行改變,如果改變就不能使用之前建立好的stream,需要重新建立。根據狀態碼判斷如果不需要重新連接,則該請求直接返回Response,工作結束!

2.BridgeInterceptor

當在RetryAndFollowUpInterceptor攔截器中調用攔截器鏈的執行方法時,將會被執行的就是BridgeInterceptor攔截器,先從源碼分析再講解原理.

2.1 源碼分析

根據之前說的BridgeInterceptor的作用,就是把用戶傳來的Request轉換成符合網絡請求格式的Request,把網絡返回的Response(可能被壓縮過)轉換成用戶可以用的Response,所以該攔截器就是對RequestResponse做操作

 @Override 
 public Response intercept(Chain chain) throws IOException {
    Request userRequest = chain.request();
    Request.Builder requestBuilder = userRequest.newBuilder();
    //requestBuilder就是根據用戶傳來的Request創建一個請求構造,添加上一些請求字段
    RequestBody body = userRequest.body();//獲取請求體,一般請求體不需要被改變
    if (body != null) {
      MediaType contentType = body.contentType();
      if (contentType != null) {
       //添加Content-type字段
        requestBuilder.header("Content-Type", contentType.toString());
      }

      long contentLength = body.contentLength();
      if (contentLength != -1) {
      //添加content-length字段
        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) {
    //添加host字段
      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; //是否支持Gzip壓縮的標誌位
    if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
    //如果用戶的接受編碼爲空,也就是對接受Response的編碼沒有要求,則允許Gzip壓縮編碼
      transparentGzip = true;
      requestBuilder.header("Accept-Encoding", "gzip");
    }

    List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
    //支持cookies
    if (!cookies.isEmpty()) {
      requestBuilder.header("Cookie", cookieHeader(cookies));
    }

    if (userRequest.header("User-Agent") == null) {
    //指定發起請求的平臺,引擎,版本號等信息
      requestBuilder.header("User-Agent", Version.userAgent());
    }

   //對Reuqest的設置好了,再接着調用下一個攔截器獲得Response,然後對Response進行處理返回給用戶
    Response networkResponse = chain.proceed(requestBuilder.build());

    HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());

//着手根據網絡返回的Response構建返回給用戶的Response
    Response.Builder responseBuilder = networkResponse.newBuilder()
        .request(userRequest);

    if (transparentGzip
        && "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
        && HttpHeaders.hasBody(networkResponse)) {
        //這是個複雜的判斷邏輯,首先就是我們允許了Gzip編碼,
       // 第二個是響應的內容編碼確實Gzip編碼,第三個就是Response有返回體,
       //任何一個條件不成立都沒必要執行這一步
      GzipSource responseBody = new GzipSource(networkResponse.body().source());
      Headers strippedHeaders = networkResponse.headers().newBuilder()
          .removeAll("Content-Encoding")
          .removeAll("Content-Length")
          .build();
          //上面的這一系列操作,就是移除一系列頭部,只返回重要信息給用戶
      responseBuilder.headers(strippedHeaders);
      String contentType = networkResponse.header("Content-Type");
      responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
    }
    //返回最後處理好的Response,retryAndFollowUpInterceptor就是根據此結果
    //判斷是否要重試。
    return responseBuilder.build();
  }

2.2 工作原理

BridgeInterceptor原理:對用戶傳入的請求做處理,在程序員編寫代碼時只需要指定Url和請求體,但是事實上,一個完整的請求報文遠不止這些信息,BridgeInterceptor幫我們做了這些事,添加各種請求報文所需要的字段,然後再傳遞給下一個攔截器去執行。對於得到的返回結果Response,其內容可能經過了Gzip壓縮,所以BridgeInterceptor幫我們做了解壓縮。這像極了愛情!!!

3.CacheInterceptor

CacheInterceptor的的作用就是緩存網絡請求,注意只能緩存GET類型的請求。他是怎麼實現緩存的呢?看一下源碼一探究竟。

3.1 源碼解析

@Override
 public Response intercept(Chain chain) throws IOException {
 //cache是構建緩存攔截器時指定的
 //根據Request的url判斷是否有緩存
    Response cacheCandidate = cache != null
        ? cache.get(chain.request())
        : null;
    long now = System.currentTimeMillis();
      //緩存策略,會有詳細介紹
      //當有請求到達時,需要判斷該請求是否有緩存,該緩存是否可用,依次構建策略
    CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
    //如果networkRequest==null,就調用緩存
    Request networkRequest = strategy.networkRequest;
    //如果cacheResponse==null,就是用網絡請求
    Response cacheResponse = strategy.cacheResponse;
    //如果兩者都爲null,則返回fail
    if (cache != null) {
    //這裏的cache是在我們創建OkhttpClient時指定的
      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 {
    //調用下一個攔截器獲取Response
      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 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 (cache != null) {
      if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
        // Offer this request to the cache.
        CacheRequest cacheRequest = cache.put(response);
        //這一步是真正的向緩存中添加Response
        return cacheWritingResponse(cacheRequest, response);
      }

      if (HttpMethod.invalidatesCache(networkRequest.method())) {
        try {
          cache.remove(networkRequest);
        } catch (IOException ignored) {
          // The cache cannot be written.
        }
      }
    }

    return response;
  }

CacheInterceptor的源碼有點亂,需要多看幾遍,這裏在說一下緩存策略以及緩存的存取

緩存策略作用的描述

Given a request and cached response, 
this figures out whether to use the network, the cache, or  both.

給定一個請求和緩存的Response,他能夠幫助我們決定是否使用網絡,使用緩存或者都是。

重要代碼展示:如何通過傳入請求和緩存得到策略的

 private CacheStrategy getCandidate() {
      // No cached response.
      if (cacheResponse == null) {
      //如果沒有緩存,則進行網絡請求
        return new CacheStrategy(request, null);
      }

      // Drop the cached response if it's missing a required handshake.
      if (request.isHttps() && cacheResponse.handshake() == null) {
      //如果是https請求並且握手信息丟失,也需要進行網絡請求
        return new CacheStrategy(request, null);
      }

      // If this response shouldn't have been stored, it should never be used
      // as a response source. This check should be redundant as long as the
      // persistence store is well-behaved and the rules are constant.
      if (!isCacheable(cacheResponse, request)) {
      //判斷請求是否可以被緩存,如果不可以,直接使用網絡
        return new CacheStrategy(request, null);
      }

    CacheControl requestCaching = request.cacheControl();
      if (requestCaching.noCache() || hasConditions(request)) {
        return new CacheStrategy(request, null);
      }

      CacheControl responseCaching = cacheResponse.cacheControl();
//從這裏開始
      long ageMillis = cacheResponseAge();
      long freshMillis = computeFreshnessLifetime();

      if (requestCaching.maxAgeSeconds() != -1) {
        freshMillis = Math.min(freshMillis, SECONDS.toMillis(requestCaching.maxAgeSeconds()));
      }

      long minFreshMillis = 0;
      if (requestCaching.minFreshSeconds() != -1) {
        minFreshMillis = SECONDS.toMillis(requestCaching.minFreshSeconds());
      }

      long maxStaleMillis = 0;
      if (!responseCaching.mustRevalidate() && requestCaching.maxStaleSeconds() != -1) {
        maxStaleMillis = SECONDS.toMillis(requestCaching.maxStaleSeconds());
      }
//到這裏結束,就是爲了判斷緩存是否過期,具體細節無需要關注。
      if (!responseCaching.noCache() && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) {
        Response.Builder builder = cacheResponse.newBuilder();
        if (ageMillis + minFreshMillis >= freshMillis) {
          builder.addHeader("Warning", "110 HttpURLConnection \"Response is stale\"");
        }
        long oneDayMillis = 24 * 60 * 60 * 1000L;
        if (ageMillis > oneDayMillis && isFreshnessLifetimeHeuristic()) {
          builder.addHeader("Warning", "113 HttpURLConnection \"Heuristic expiration\"");
        }
        return new CacheStrategy(null, builder.build());
      }

      // Find a condition to add to the request. If the condition is satisfied, the response body
      // will not be transmitted.
      //流程走到這,說明緩存已經過期了
      //添加請求頭:If-Modified-Since或者If-None-Match
      //etag與If-None-Match配合使用
      //lastModified與If-Modified-Since配合使用
      //前者和後者的值是相同的
      //區別在於前者是響應頭,後者是請求頭。
      //後者用於服務器進行資源比對,看看是資源是否改變了。
      // 如果沒有,則本地的資源雖過期還是可以用的
      String conditionValue;
      if (etag != null) {
      //默認是null的
        conditionName = "If-None-Match";
        conditionValue = etag;
      } else if (lastModified != null) {
      //The last modified date of the cached response, if known.
        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);
    }

緩存策略並不複雜,還有緩存的存取採用的是DiskLru,根據urlmd5hex值作爲鍵去存取,想要深入的可以看一下DiskLruCahce的源碼。

3.2 工作原理

原理:底層是基於DiskLruCache,對於一個請求,
1.沒有緩存,直接網絡請求;
2.如果是https,但沒有握手,直接網絡請求;
3.不可緩存,直接網絡請求;
4.請求頭nocache或者請求頭包含If-Modified-Since或者If-None-Match,則需要服務器驗證本地緩存是不是還能繼續使用,直接網絡請求;
5.可緩存,並且ageMillis + minFreshMillis < freshMillis + maxStaleMillis(意味着雖過期,但可用,只是會在響應頭添加warning),則使用緩存;
6.緩存已經過期,添加請求頭:If-Modified-Since或者If-None-Match,進行網絡請求;

4.總結

剩下兩個攔截器會在下一篇博客講解,最後還會有個對Okhttp總體的整理和相關的面試題!
先別走,我有一個資源學習羣要推薦給你,它是白嫖黨的樂園,小白的天堂!
在這裏插入圖片描述
別再猶豫,一起來學習!
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章