Android OkHttp(一)原始碼出發探尋執行原理

艾陽丶發表於2017-05-17

    現在主流的網路請求都是使用 Retrofit + OkHttp ,在掌握了一般使用後,就要往深裡探究框架原始碼,這樣不光是為了面試裝逼,更是提升了對原始碼理解能力。經過大約一週的時間準備,原始碼看了個大概,也就大致明白了原理,這裡總結一下整理成文,希望對大家能有所幫助。

推薦文章:

Android 必須知道的網路請求框架庫,你不可錯過的框架介紹篇

Android Retrofit 2.0(一)初次見面請多多關照

Android Retrofit 2.0(二)使用教程OkHttp3 + Gson + RxJava

Android Retrofit 2.0(三)從原始碼分析原理

流程結構

首先,OkHttpClient 通過Builder構建 Request(url\method\header\body) 轉換為 newCall;

然後,在 RealCall 中執行非同步或同步任務;

最後,配合一些攔截器 interceptor 傳送請求得到返回 response(code\message\headers\body)。

——OkHttp流程圖,如下:

 

Get請求過程

案例是,假設我們正在進行一個普通的okhttp進行同步請求,然後我們按照前面的流程圖依次進行分析,簡單易懂。

    public String get(String url) throws IOException {
        //建立 OKHttpClient物件
        OkHttpClient client = new OkHttpClient();
        //建立 Request物件
        Request request = new Request.Builder()
                .url(url)
                .build();
        //建立 Response接收響應
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        }else{
            throw new IOException("Unexpected code " + response);
        }
    }

1、建立 OKHttpClient 物件

OkHttpClient client = new OkHttpClient();

該物件包括以下內容:

    final Dispatcher dispatcher;  //分發器
    final Proxy proxy;  //代理
    final List<Protocol> protocols; //協議
    final List<ConnectionSpec> connectionSpecs; //傳輸層版本和連線協議
    final List<Interceptor> interceptors; //攔截器
    final List<Interceptor> networkInterceptors; //網路攔截器
    final ProxySelector proxySelector; //代理選擇
    final CookieJar cookieJar; //cookie
    final Cache cache; //快取
    final InternalCache internalCache;  //內部快取
    final SocketFactory socketFactory;  //socket 工廠
    final SSLSocketFactory sslSocketFactory; //安全套接層socket 工廠,用於HTTPS
    final CertificateChainCleaner certificateChainCleaner; // 驗證確認響應證照 適用 HTTPS 請求連線的主機名。
    final HostnameVerifier hostnameVerifier;    //  主機名字確認
    final CertificatePinner certificatePinner;  //  證照鏈
    final Authenticator proxyAuthenticator;     //代理身份驗證
    final Authenticator authenticator;      // 本地身份驗證
    final ConnectionPool connectionPool;    //連線池,複用連線
    final Dns dns;  //域名
    final boolean followSslRedirects;  //安全套接層重定向
    final boolean followRedirects;  //本地重定向
    final boolean retryOnConnectionFailure; //重試連線失敗
    final int connectTimeout;    //連線超時
    final int readTimeout; //read 超時
    final int writeTimeout; //write 超時

可以看出 OkHttpClient 相當於OKhttp網路請求的配置控制器。另外,OkHttpClient是建造者模式實現的,我們可以改變配置的一些引數,然後通過builder()方法進行構建,如果我們不手動設定,它就會使用預設的設定,如下:

            dispatcher = new Dispatcher();
            protocols = DEFAULT_PROTOCOLS;
            connectionSpecs = DEFAULT_CONNECTION_SPECS;
            proxySelector = ProxySelector.getDefault();
            cookieJar = CookieJar.NO_COOKIES;
            socketFactory = SocketFactory.getDefault();
            hostnameVerifier = OkHostnameVerifier.INSTANCE;
            certificatePinner = CertificatePinner.DEFAULT;
            proxyAuthenticator = Authenticator.NONE;
            authenticator = Authenticator.NONE;
            connectionPool = new ConnectionPool();
            dns = Dns.SYSTEM;
            followSslRedirects = true;
            followRedirects = true;
            retryOnConnectionFailure = true;
            connectTimeout = 10_000;
            readTimeout = 10_000;
            writeTimeout = 10_000;

2、newCall()方法

        @Override
        public Call newCall(Request request) {
            return new RealCall(this, request);
        }

準備要執行request:當通過建造者模式建立了Request之後,

再通過 Response response = client.newCall(request).execute();  開啟GET請求的流程。

3、RealCall()方法

protected RealCall(OkHttpClient client, Request originalRequest) {  
    this.client = client;    
    this.originalRequest = originalRequest;    
    this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client);
}

真正的執行request:傳一個 OkHttpClient 物件和 originalRequest 物件。

4、execute()方法

 @Override
    public Response execute() throws IOException {
        synchronized (this) {
            if (executed) throw new IllegalStateException("Already Executed"); //(1)
            executed = true;
        }
        try {
            client.dispatcher.executed(this);//(2)
            Response result = getResponseWithInterceptorChain();//(3)
            if (result == null) throw new IOException("Canceled");
            return result;
        }finally {
            client.dispatcher.finished(this);//(4)
        }
    }
1、加了同步鎖 synchronized ,並檢查 call 是否已被執行,每個 call 只能被執行一次。
2、進行實際執行。dispatcher 是 OkHttpClient.Builder 的一個成員,是 HTTP 請求的執行策略。
3、進行一系列“攔截”操作,並獲取 HTTP 返回結果。(下一個就要說它)

4、通知 dispatcher 已經執行完畢。

5、getResponseWithInterceptorChain()


攔截器的責任鏈:真正發出網路請求、解析返回結果的重要方法!!! 

 private Response getResponseWithInterceptorChain() throws IOException {
     // Build a full stack of interceptors.
     List<Interceptor> interceptors = new ArrayList<>();
     interceptors.addAll(client.interceptors());     //(1)
     interceptors.add(retryAndFollowUpInterceptor);    //(2)
     interceptors.add(new BridgeInterceptor(client.cookieJar()));    //(3)
     interceptors.add(new CacheInterceptor(client.internalCache()));    //(4)
     interceptors.add(new ConnectInterceptor(client));    //(5)
     if (!retryAndFollowUpInterceptor.isForWebSocket()) {
         interceptors.addAll(client.networkInterceptors());    //(6)
     }
     interceptors.add(new CallServerInterceptor(
             retryAndFollowUpInterceptor.isForWebSocket()));     //(7)

     Interceptor.Chain chain = new RealInterceptorChain(
             interceptors, null, null, null, 0, originalRequest);
     return chain.proceed(originalRequest); //(8)
 }
  1. 在配置 OkHttpClient 時設定一些 interceptors 攔截器們;
  2. 負責失敗重試以及重定向的 RetryAndFollowUpInterceptor 攔截器;
  3. 負責把使用者的請求轉換為傳送到伺服器的請求和把伺服器的返回轉換為使用者友好響應的攔截器;
  4. 負責讀取快取直接返回、更新快取的攔截器;
  5. 負責和伺服器建立連線的攔截器;
  6. 負責建立網路關係的攔截器;
  7. 負責向伺服器傳送請求、從伺服器讀取響應資料的攔截器。(下一個會說它)
  8. 開啟鏈式呼叫:

6、RealInterceptorChain()

public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
      Connection connection) throws IOException {
    if (index >= interceptors.size()) throw new AssertionError();
    calls++;
    //如果我們已經有一個stream。確定即將到來的request會使用它
    if (this.httpCodec != null && !sameConnection(request.url())) {
      throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
          + " must retain the same host and port");
    }
    //如果我們已經有一個stream, 確定chain.proceed()唯一的call
    if (this.httpCodec != null && calls > 1) {
      throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
          + " must call proceed() exactly once");
    }
    //呼叫鏈的下一個攔截器
    RealInterceptorChain next = new RealInterceptorChain(
        interceptors, streamAllocation, httpCodec, connection, index + 1, request);
    Interceptor interceptor = interceptors.get(index);
    Response response = interceptor.intercept(next);
    if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
      throw new IllegalStateException("network interceptor " + interceptor
          + " must call proceed() exactly once");
    }
    if (response == null) {
      throw new NullPointerException("interceptor " + interceptor + " returned null");
    }
    return response;
  }

程式碼很多,主要程式碼如下:

    //呼叫鏈的下一個攔截器
    RealInterceptorChain next = new RealInterceptorChain(
        interceptors, streamAllocation, httpCodec, connection, index + 1, request);    //(1)
    Interceptor interceptor = interceptors.get(index);     //(2)
    Response response = interceptor.intercept(next);    //(3)
1、例項化下一個攔截器對應的RealIterceptorChain物件,這個物件會在傳遞給當前的攔截器;
2、得到當前的攔截器:interceptors是存放攔截器的ArryList;
3、呼叫當前攔截器的intercept()方法,並將下一個攔截器的RealIterceptorChain物件傳遞下去


下面說負責失敗重試以及重定向 :retryAndFollowUpInterceptor攔截器

7、RetryAndFollowUpInterceptor()

@Override 
public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        streamAllocation = new StreamAllocation(
                client.connectionPool(), createAddress(request.url()));
        int followUpCount = 0;
        Response priorResponse = null;
        while (true) {
            if (canceled) {
                streamAllocation.release();
                throw new IOException("Canceled");
            }
            Response response = null;
            boolean releaseConnection = true;
            try {
                response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);    //(1)
                releaseConnection = false;
            } catch (RouteException e) {
                //通過路線連線失敗,請求將不會再傳送
                if (!recover(e.getLastConnectException(), true, request)) throw e.getLastConnectException();
                releaseConnection = false;
                continue;
            } catch (IOException e) {
                // 與伺服器嘗試通訊失敗,請求不會再傳送。
                if (!recover(e, false, request)) throw e;
                releaseConnection = false;
                continue;
            } finally {
                //丟擲未檢查的異常,釋放資源
                if (releaseConnection) {
                    streamAllocation.streamFailed(null);
                    streamAllocation.release();
                }
            }
            // 附加上先前存在的response。這樣的response從來沒有body
            if (priorResponse != null) {
                response = response.newBuilder()
                        .priorResponse(priorResponse.newBuilder()
                                .body(null)
                                .build())
                        .build();
            }
            Request followUp = followUpRequest(response); //判斷狀態碼 (2)
            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) {
                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()));
            } 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;
        }
    }

1、這裡是最關鍵的程式碼,可以看出再這裡直接呼叫了下一個攔截器,然後捕獲可能的異常來進行操作;

2、這裡對於返回的response的狀態碼進行判斷,然後進行處理。

下面說,負責把使用者的請求轉換為傳送到伺服器的請求和把伺服器的返回轉換為使用者友好響應的攔截器:

8、BridgeInterceptor()

@Override 
public Response intercept(Chain chain) throws IOException {
    Request userRequest = chain.request();
    Request.Builder requestBuilder = userRequest.newBuilder();
    //檢查request。將使用者的request轉換為傳送到server的請求
    RequestBody body = userRequest.body();     //(1)
    if (body != null) {
      MediaType contentType = body.contentType();
      if (contentType != null) {
        requestBuilder.header("Content-Type", contentType.toString());
      }
      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");
      }
    }
    if (userRequest.header("Host") == null) {
      requestBuilder.header("Host", hostHeader(userRequest.url(), false));
    }
    if (userRequest.header("Connection") == null) {
      requestBuilder.header("Connection", "Keep-Alive");
    }
    //GZIP壓縮
    boolean transparentGzip = false;
    if (userRequest.header("Accept-Encoding") == null) {
      transparentGzip = true;
      requestBuilder.header("Accept-Encoding", "gzip");
    }
    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());
    }
    Response networkResponse = chain.proceed(requestBuilder.build());   //(2)
    HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers()); //(3)
    Response.Builder responseBuilder = networkResponse.newBuilder()
        .request(userRequest);
    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();
  }

1、下面一段程式碼都是 BridgeInterceptor 對於 request 的格式進行檢查,讓構建了一個新的request;

2、呼叫下一個interceptor來得到response;

3、下面都是對得到的response進行一些判斷操作,最後將結果返回。

@Override 
public Response intercept(Chain chain) throws IOException {
    Response cacheCandidate = cache != null   //(1)
        ? cache.get(chain.request()) //通過request得到快取
        : null;
    long now = System.currentTimeMillis();
    CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get(); //(2)
    Request networkRequest = strategy.networkRequest;
    Response cacheResponse = strategy.cacheResponse;
    if (cache != null) {
      cache.trackResponse(strategy);
    }
    if (cacheCandidate != null && cacheResponse == null) { //存在快取的response,但是不允許快取
      closeQuietly(cacheCandidate.body()); // 快取不適合,關閉
    }
      //如果我們禁止使用網路,且快取為null,失敗
    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(EMPTY_BODY)
          .sentRequestAtMillis(-1L)
          .receivedResponseAtMillis(System.currentTimeMillis())
          .build();
    }
    if (networkRequest == null) {  //沒有網路請求,跳過網路,返回快取
      return cacheResponse.newBuilder()
          .cacheResponse(stripBody(cacheResponse))
          .build();
    }
    Response networkResponse = null;
    try {
      networkResponse = chain.proceed(networkRequest);//網路請求攔截器    //======(3)
    } finally {
        //如果我們因為I/O或其他原因崩潰,不要洩漏快取體
      if (networkResponse == null && cacheCandidate != null) {
        closeQuietly(cacheCandidate.body());
      }
    }
    //(4)
      //如果我們有一個快取的response,然後我們正在做一個條件GET
    if (cacheResponse != null) {
      if (validate(cacheResponse, networkResponse)) { //比較確定快取response可用
        Response response = cacheResponse.newBuilder()
            .headers(combine(cacheResponse.headers(), networkResponse.headers()))
            .cacheResponse(stripBody(cacheResponse))
            .networkResponse(stripBody(networkResponse))
            .build();
        networkResponse.body().close();
         //更新快取,在剝離content-Encoding之前
        cache.trackConditionalCacheHit();
        cache.update(cacheResponse, response);
        return response;
      } else {
        closeQuietly(cacheResponse.body());
      }
    }
    Response response = networkResponse.newBuilder()
        .cacheResponse(stripBody(cacheResponse))
        .networkResponse(stripBody(networkResponse))
        .build();
    if (HttpHeaders.hasBody(response)) {    // (5)
      CacheRequest cacheRequest = maybeCache(response, networkResponse.request(), cache);
      response = cacheWritingResponse(cacheRequest, response);
    }
    return response;
  }
  • 首先,根據request來判斷cache中是否有快取的response,如果有,得到這個response,然後進行判斷當前response是否有效,沒有將cacheCandate賦值為空。
  • 根據request判斷快取的策略,是否要使用了網路,快取 或兩者都使用
  • 呼叫下一個攔截器,決定從網路上來得到response
  • 如果本地已經存在cacheResponse,那麼讓它和網路得到的networkResponse做比較,決定是否來更新快取的cacheResponse
  • 快取未經快取過的response

9、ConnectInterceptor()建立連線

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

    boolean doExtensiveHealthChecks = !request.method().equals("GET");
    HttpCodec httpCodec = streamAllocation.newStream(client, doExtensiveHealthChecks);
    RealConnection connection = streamAllocation.connection();

    return realChain.proceed(request, streamAllocation, httpCodec, connection);
}

實際上建立連線就是建立了一個 HttpCodec 物件,它將在後面的步驟中被使用,那它又是何方神聖呢?它是對 HTTP 協議操作的抽象,有兩個實現:Http1Codec和Http2Codec,顧名思義,它們分別對應 HTTP/1.1 和 HTTP/2 版本的實現。
在Http1Codec中,它利用 Okio 對Socket的讀寫操作進行封裝,Okio 以後有機會再進行分析,現在讓我們對它們保持一個簡單地認識:它對java.io和java.nio進行了封裝,讓我們更便捷高效的進行 IO 操作。
而建立HttpCodec物件的過程涉及到StreamAllocation、RealConnection,程式碼較長,這裡就不展開,這個過程概括來說,就是找到一個可用的RealConnection,再利用RealConnection的輸入輸出(BufferedSource和BufferedSink)建立HttpCodec物件,供後續步驟使用。

10、CallServerInterceptor()傳送和接收資料

 @Override public Response intercept(Chain chain) throws IOException {
    HttpCodec httpCodec = ((RealInterceptorChain) chain).httpStream();
    StreamAllocation streamAllocation = ((RealInterceptorChain) chain).streamAllocation();
    Request request = chain.request();
    long sentRequestMillis = System.currentTimeMillis();
    httpCodec.writeRequestHeaders(request);
    if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {   //===(1)
      Sink requestBodyOut = httpCodec.createRequestBody(request, request.body().contentLength());
      BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
      request.body().writeTo(bufferedRequestBody);
      bufferedRequestBody.close();
    }
    httpCodec.finishRequest();
    Response response = httpCodec.readResponseHeaders()     //====(2)
        .request(request)
        .handshake(streamAllocation.connection().handshake())
        .sentRequestAtMillis(sentRequestMillis)
        .receivedResponseAtMillis(System.currentTimeMillis())
        .build();
    if (!forWebSocket || response.code() != 101) {
      response = response.newBuilder()
          .body(httpCodec.openResponseBody(response))
          .build();
    }
    if ("close".equalsIgnoreCase(response.request().header("Connection"))
        || "close".equalsIgnoreCase(response.header("Connection"))) {
      streamAllocation.noNewStreams();
    }
    int code = response.code();
    if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
      throw new ProtocolException(
          "HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
    }
    return response;
  }
  1. 檢查請求方法,用Httpcodec處理request;
  2. 進行網路請求得到response;
  3. 返回response。

小結:前面說了攔截器用了責任鏈設計模式,它將請求一層一層向下傳,知道有一層能夠得到Resposne就停止向下傳遞,然後將response向上面的攔截器傳遞,然後各個攔截器會對respone進行一些處理,最後會傳到RealCall類中通過execute來得到esponse。


非同步請求流程分析

private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://publicobject.com/helloworld.txt")
        .build();

    client.newCall(request).enqueue(new Callback() {
      @Override 
      public void onFailure(Call call, IOException e) {
        e.printStackTrace();
      }

      @Override 
      public void onResponse(Call call, Response response) throws IOException {
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
        Headers responseHeaders = response.headers();
        for (int i = 0, size = responseHeaders.size(); i < size; i++) {
          System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
        }
        System.out.println(response.body().string());
      }
    });
  }

由程式碼中client.newCall(request).enqueue(Callback),開始我們知道client.newCall(request)方法返回的是RealCall物件,接下來繼續向下看enqueue()方法:

 //非同步任務使用
    @Override 
    public void enqueue(Callback responseCallback) {
        synchronized (this) {
            if (executed) throw new IllegalStateException("Already Executed");
            executed = true;
        }
        client.dispatcher().enqueue(new AsyncCall(responseCallback));
    }

呼叫了上面我們沒有詳細說的Dispatcher類中的enqueue(Call )方法.接著繼續看:

synchronized void enqueue(AsyncCall call) {
        if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
            runningAsyncCalls.add(call);
            executorService().execute(call);
        } else {
            readyAsyncCalls.add(call);
        }
    }

如果中的runningAsynCalls不滿,且call佔用的host小於最大數量,則將call加入到runningAsyncCalls中執行,同時利用執行緒池執行call;否者將call加入到readyAsyncCalls中。runningAsyncCalls和readyAsyncCalls是什麼呢?看下面:

/** Ready async calls in the order they'll be run. */
private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>(); //正在準備中的非同步請求佇列

/** Running asynchronous calls. Includes canceled calls that haven't finished yet. */
private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>(); //執行中的非同步請求

/** Running synchronous calls. Includes canceled calls that haven't finished yet. */
private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>(); //同步請求

call加入到執行緒池中執行了。現在再看AsynCall的程式碼,它是RealCall中的內部類:

//非同步請求
    final class AsyncCall extends NamedRunnable {
        private final Callback responseCallback;

        private AsyncCall(Callback responseCallback) {
            super("OkHttp %s", redactedUrl());
            this.responseCallback = responseCallback;
        }

        String host() {
            return originalRequest.url().host();
        }

        Request request() {
            return originalRequest;
        }

        RealCall get() {
            return RealCall.this;
        }

        @Override protected void execute() {
            boolean signalledCallback = false;
            try {
                Response response = getResponseWithInterceptorChain();
                if (retryAndFollowUpInterceptor.isCanceled()) {
                    signalledCallback = true;
                    responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
                } else {
                    signalledCallback = true;
                    responseCallback.onResponse(RealCall.this, response);
                }
            } catch (IOException e) {
                if (signalledCallback) {
                    // Do not signal the callback twice!
                    Platform.get().log(INFO, "Callback failure for " + toLoggableString(), e);
                } else {
                    responseCallback.onFailure(RealCall.this, e);
                }
            } finally {
                client.dispatcher().finished(this);
            }
        }
    }

AysncCall中的execute()中的方法,同樣是通過Response response = getResponseWithInterceptorChain();來獲得response,這樣非同步任務也同樣通過了interceptor,剩下的流程就和上面一樣了。

束。


相關文章