OKHTTP解析

什么是OKHttp?

OKHttp是一個非常優秀的網絡操作框架,它已經被谷歌收錄到Android源碼。目前比較流行的Retrofit也是默認使用OkHttp的。

怎樣使用它?

OK HTTP使用流程

OkHttpClient(流程的總控制者)

在Client對象里你會發現它是通過構建者模式來創建的



它里面主要有哪些參數呢?


參數.png
 final Dispatcher dispatcher;//調度對象(也可以稱為分發器)
 final @Nullable Proxy proxy;// 代理                                                                    
 final List<Protocol> protocols;//協議
 final List<ConnectionSpec> connectionSpecs;//連接規格(傳輸層版本,連接協議)
 final List<Interceptor> interceptors;//攔截器
 final List<Interceptor> networkInterceptors;//網絡攔截器
 final EventListener.Factory eventListenerFactory;//事件列表工廠
 final ProxySelector proxySelector;//主動選擇器(代理選擇)
 final CookieJar cookieJar;//cookie
 final @Nullable Cache cache;//緩存
 final @Nullable InternalCache internalCache;//內存緩存
 final SocketFactory socketFactory;//socket工廠
 final @Nullable SSLSocketFactory sslSocketFactory;//SSLSocket工廠
 final @Nullable 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 超時 
 final int pingInterval;//平區間
Builder方法

OKHttp真正的流程是從newCall方法開始的

  @Override
 public Call newCall(Request request) {
         return RealCall.newRealCall(this, request, false /* for web socket */);
}

它的返回值是一個RealCall,下面我們看看RealCall的構造方法

  private RealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
      this.client = client;
      this.originalRequest = originalRequest;
      this.forWebSocket = forWebSocket;
      this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client, forWebSocket);
 }
 static RealCall newRealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
     // Safely publish the Call instance to the EventListener.
     RealCall call = new RealCall(client, originalRequest, forWebSocket);
     call.eventListener = client.eventListenerFactory().create(call);
    return call;
}

RealCall中構造方法中OriginalRequest對象就是request對象。接下來就是execute()方法

 @Override 
 public Response execute() throws IOException {
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    captureCallStackTrace();
    eventListener.callStart(this);
    try {
      client.dispatcher().executed(this);
      Response result = getResponseWithInterceptorChain();
      if (result == null) throw new IOException("Canceled");
      return result;
    } catch (IOException e) {
      eventListener.callFailed(this, e);
      throw e;
    } finally {
      client.dispatcher().finished(this);
   }
  }

1.檢查這個 call是否已經被執行了,每個 call 只能被執行一次,如果想要一個完全一樣的 call,可以利用 clone 方法進行克隆。

 @Override 
public RealCall clone() {
    return RealCall.newRealCall(client, originalRequest, forWebSocket);
 }

2.利用 client.dispatcher().executed(this) 來進行實際執行,dispatcher 是剛才看到的 OkHttpClient.Builder 的成員之一,它的文檔說自己是異步 HTTP請求的執行策略,現在看來,同步請求它也有摻和。

3.調用 getResponseWithInterceptorChain() 函數獲取 HTTP 返回結果,從函數名可以看出,這一步還會進行一系列“攔截”操作。

4.最后還要通知 dispatcher 自己已經執行完畢。dispatcher在同步執行的流程中,涉及到 dispatcher 的內容只不過是告知它我們的執行狀態,比如開始執行了(調用 executed),比如執行完畢了(調用 finished),在異步執行流程中它會有更多的參與。真正發出網絡請求,解析返回結果的,還是 getResponseWithInterceptorChain:

 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 (!forWebSocket) {
      interceptors.addAll(client.networkInterceptors());//(6)
    }
    interceptors.add(new CallServerInterceptor(forWebSocket));//(7)

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

    return chain.proceed(originalRequest);
}

(1)在配置 OkHttpClient 時設置的 interceptors;
(2)負責失敗重試以及重定向的 RetryAndFollowUpInterceptor(后繼攔截器);
(3)負責把用戶構造的請求轉換為發送到服務器的請求、把服務器返回的響應轉換為用戶友好的響應的 BridgeInterceptor(橋氏攔截器);
(4)負責讀取緩存直接返回、更新緩存的 CacheInterceptor(緩存攔截器);
(5)負責和服務器建立連接的 ConnectInterceptor(連接攔截器);
(6)配置 OkHttpClient 時設置的 networkInterceptors(網絡攔截器);
(7)負責向服務器發送請求數據、從服務器讀取響應數據的 CallServerInterceptor(調用攔截器)。
(8)在return chain.proceed(originalRequest);中開啟鏈式調用:

RealInterceptorChain

public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
      Connection connection) throws IOException {
    if (index >= interceptors.size()) throw new AssertionError();

    calls++;

    // If we already have a stream, confirm that the incoming request will use it.
    //如果我們已經有一個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");
    }

    // If we already have a stream, confirm that this is the only call to chain.proceed().
    //如果我們已經有一個stream, 確定chain.proceed()唯一的call
    if (this.httpCodec != null && calls > 1) {
      throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
          + " must call proceed() exactly once");
    }

    // Call the next interceptor in the chain.
    //調用鏈的下一個攔截器
    RealInterceptorChain next = new RealInterceptorChain(
        interceptors, streamAllocation, httpCodec, connection, index + 1, request);
    Interceptor interceptor = interceptors.get(index);
    Response response = interceptor.intercept(next);

    // Confirm that the next interceptor made its required call to chain.proceed().
    if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
      throw new IllegalStateException("network interceptor " + interceptor
          + " must call proceed() exactly once");
    }

    // Confirm that the intercepted response isn't null.
    if (response == null) {
      throw new NullPointerException("interceptor " + interceptor + " returned null");
    }

    return response;
  }

最主要的代碼是這點

   // Call the next interceptor in the chain.
   //調用鏈的下一個攔截器
    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對象傳遞下去
    除了在client中自己設置的interceptor,第一個調用的就是retryAndFollowUpInterceptor

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) {
                // The attempt to connect via a route failed. The request will not have been sent.
                //通過路線連接失敗,請求將不會再發送
                if (!recover(e.getLastConnectException(), true, request)) throw e.getLastConnectException();
                releaseConnection = false;
                continue;
            } catch (IOException e) {
                // An attempt to communicate with a server failed. The request may have been sent.
                // 與服務器嘗試通信失敗,請求不會再發送。
                if (!recover(e, false, 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.
            // 附加上先前存在的response。這樣的response從來沒有body
            // TODO: 2016/8/23 這里沒賦值,豈不是一直為空?
            if (priorResponse != null) { //  (2)
                response = response.newBuilder()
                        .priorResponse(priorResponse.newBuilder()
                                .body(null)
                                .build())
                        .build();
            }

            Request followUp = followUpRequest(response); //判斷狀態碼 (3)
            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. 這里是最關鍵的代碼,可以看出在response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);中直接調用了下一個攔截器,然后捕獲可能的異常來進行操作
  2. 這里沒看太懂,有點坑,以后補
  3. 這里對于返回的response的狀態碼進行判斷,然后進行處理

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");
    }
      // If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing
    // the transfer stream.
    //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. 在(1)和(2)之間,BridgeInterceptor對于request的格式進行檢查,讓構建了一個新的request
  2. 調用下一個interceptor來得到response
  3. (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(); //根據request來得到緩存策略===========(2)
    Request networkRequest = strategy.networkRequest;
    Response cacheResponse = strategy.cacheResponse;

    if (cache != null) {
      cache.trackResponse(strategy);
    }

    if (cacheCandidate != null && cacheResponse == null) { //存在緩存的response,但是不允許緩存
      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.
      //如果我們禁止使用網絡,且緩存為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 we don't need the network, we're done.
    if (networkRequest == null) {  //沒有網絡請求,跳過網絡,返回緩存
      return cacheResponse.newBuilder()
          .cacheResponse(stripBody(cacheResponse))
          .build();
    }

    Response networkResponse = null;
    try {
      networkResponse = chain.proceed(networkRequest);//網絡請求攔截器    //======(3)
    } finally {
      // If we're crashing on I/O or otherwise, don't leak the cache body.
        //如果我們因為I/O或其他原因崩潰,不要泄漏緩存體
      if (networkResponse == null && cacheCandidate != null) {
        closeQuietly(cacheCandidate.body());
      }
    }

    // If we have a cache response too, then we're doing a conditional get.========(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();

        // Update the cache after combining headers but before stripping the
        // Content-Encoding header (as performed by initContentStream()).
          //更新緩存,在剝離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;
  }

  1. 首先,根據request來判斷cache中是否有緩存的response,如果有,得到這個response,然后進行判斷當前response是否有效,沒有將cacheCandate賦值為空。
  2. 根據request判斷緩存的策略,是否要使用了網絡,緩存 或兩者都使用
  3. 調用下一個攔截器,決定從網絡上來得到response
  4. 如果本地已經存在cacheResponse,那么讓它和網絡得到的networkResponse做比較,決定是否來更新緩存的cacheResponse
  5. 緩存未經緩存過的response

ConnectInterceptor:建立連接

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

       // We need the network to satisfy this request. Possibly for validating a conditional GET.
       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對象,供后續步驟使用。

NetworkInterceptors

配置OkHttpClient時設置的 NetworkInterceptors。

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。

異步請求的流程:

異步get請求示例如下:


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,剩下的流程就和上面一樣了。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容