Android - okhttp 源碼分析

知其然知其所以然,我們不做只會調(diào)用 API 的碼農(nóng),不要重復(fù)制造輪子不代表我們不應(yīng)該了解輪子的構(gòu)造!

Talk is cheap, show me the code

1. GET 請求使用

  • 異步 GET 請求
    private OkHttpClient client = new OkHttpClient();
    public void get(String url, Map<String, Object> params, Callback responseCallback) {

        HttpUrl.Builder httpBuider = HttpUrl.parse(url).newBuilder();
        if (params != null) {
            for (Map.Entry<String, Object> param : params.entrySet()) {
                httpBuider.addQueryParameter(param.getKey(), param.getValue().toString());
            }
        }
        Request request = new Request.Builder().url(httpBuider.build()).build();
        client.newCall(request).enqueue(responseCallback);
    }

    // 調(diào)用簡單的異步get請求
    findViewById(R.id.btn_get).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String url = "http://192.168.6.21:9090/get";
            HashMap<String, Object> map = new HashMap<>();
            map.put("name", "xiaocai");
            map.put("age", 25  );
            get(url, map, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String data = response.body().string();
                    Log.d("xiaocai", "response:" + data);

                }
            });
        }
    });

  springboot中簡單的處理:
    @GetMapping("/get")
    public String testGet(@RequestParam(value = "name") String name,
                          @RequestParam(value = "age", required = false) int age) {
        String data = "name:" + name + " age:" + age;
        return JsonHelper.success(data);
    }

  輸出:
  xiaocai: response:{"msg":"成功","code":0,"data":"name:xiaocai age:25","status":"0"}
  • 同步GET請求:
OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();

2. POST 請求使用

  • 異步 POST 請求
    findViewById(R.id.btn_post).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            connectEnqueue();
        }
    });


    private void connectEnqueue() {
        RequestBody formBody = new FormBody.Builder()
                .add("name", "xiaocai")
                .add("email", "xiaocai@163.com")
                .build();
        Request request = new Request.Builder().url(url)
                .post(formBody)
                .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 {
                String data = response.body().string();
                Log.d("xiaocai", "response:" + data);

            }
        });
    }

    輸出:
    {"msg":"成功","code":0,"data":"name:xiaocai email:xiaocai@163.com","status":"0"}
  • 同步 POST 請求
    private void connectExecute() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String response = connectExecute(url);
                    Log.d("xiaocai", "response:" + response);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    private String connectExecute(String url) throws IOException {
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }

    }

同步請求為「execute」,異步為「enqueue」.可以先簡單看下這兩個單詞的意思:

  • execute : vt. 實行榛瓮;執(zhí)行;處死
  • enqueue : n. 排隊袱巨;入隊删咱;隊列

從意思我們大概可以猜出它們的執(zhí)行方式了

  • execute : 是個及物動詞,為「執(zhí)行」之意,顧名思義就是直接執(zhí)行(同步).
  • enqueue : 是名詞「入隊」,所以對加入到一個隊列中,排隊等候執(zhí)行(異步).

3. 發(fā)起請求跟蹤

首先從
client.newCall(request).enqueue(responseCallback);
看里面具體執(zhí)行.該方法返回 Call 對象,是個接口.而具體實現(xiàn)在 RealCall 中,具體實行的邏輯:


  @Override public void enqueue(Callback responseCallback) {
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    captureCallStackTrace();
    client.dispatcher().enqueue(new AsyncCall(responseCallback));
  }

在這里直接傳遞給 Dispatcher 進(jìn)行分發(fā):

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

加入到異步請求集合中:

  /** Running asynchronous calls. Includes canceled calls that haven't finished yet. */
  private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();

使用線程池管理線程,不限容量:

  public synchronized ExecutorService executorService() {
    if (executorService == null) {
      executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
          new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false));
    }
    return executorService;
  }

返回來 client.newCall(request).enqueue(responseCallback); 看 AsyncCall 這個對象:

   // NamedRunnable里面事項了runnable接口
  final class AsyncCall extends NamedRunnable {
    private final Callback responseCallback;

    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();// 真正發(fā)起請求
        // 處理響應(yīng)
        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);
      }
    }
  }

這里最重要的是 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()); // 用戶自定義網(wǎng)絡(luò)攔截器
    }
    interceptors.add(new CallServerInterceptor(forWebSocket)); // 發(fā)起請求和獲得響應(yīng)的攔截器

    Interceptor.Chain chain = new RealInterceptorChain(
        interceptors, null, null, null, 0, originalRequest);
    return chain.proceed(originalRequest);
  }

添加攔截器 interceptor,從字面上不能正確的理解,其實攔截器里面才是正在做網(wǎng)絡(luò)操作的!這幾個攔截器都比較重要,接下來逐個分析.
到此我們差不多看到了一個簡單的流程,還有很多的細(xì)節(jié)慢慢進(jìn)行分析.

4. 總攔截器 RealInterceptorChain (分發(fā)攔截器)

在上面的源碼,只是添加到攔截器集合中,但真正調(diào)用攔截的是在 RealInterceptorChain 中.在這個攔截器中進(jìn)行遍歷所有攔截器,有意思的是遍歷的方式不是直接調(diào)用 for 或者一般的遞歸方法,而是取出當(dāng)前的攔截器,將角標(biāo)增1后重新構(gòu)建 RealInterceptorChain .
這里我們看到了另一種遞歸方式.


/**
 * 調(diào)用所有攔截器的攔截器,okhttpclient會將所有的攔截器傳進(jìn)來,內(nèi)部遍歷所有進(jìn)行請求
 */
public final class RealInterceptorChain implements Interceptor.Chain {
    private final List<Interceptor> interceptors;
    private final StreamAllocation streamAllocation;
    private final HttpCodec httpCodec;
    private final RealConnection connection;
    private final int index;
    private final Request request;
    private int calls;

    public RealInterceptorChain(List<Interceptor> interceptors, StreamAllocation streamAllocation,
                                HttpCodec httpCodec, RealConnection connection, int index, Request request) {
        this.interceptors = interceptors;
        this.connection = connection;
        this.streamAllocation = streamAllocation;
        this.httpCodec = httpCodec;
        this.index = index;
        this.request = request;
    }

    @Override public Connection connection() {
        return connection;
    }

    public StreamAllocation streamAllocation() {
        return streamAllocation;
    }

    public HttpCodec httpStream() {
        return httpCodec;
    }

    @Override public Request request() {
        return request;
    }

    @Override public Response proceed(Request request) throws IOException {
        return proceed(request, streamAllocation, httpCodec, connection);
    }

    public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
                            RealConnection connection) throws IOException {
        // 檢查角標(biāo)是否越界
        if (index >= interceptors.size()) throw new AssertionError();

        calls++;

        // If we already have a stream, confirm that the incoming request will use it.
        if (this.httpCodec != null && !this.connection.supportsUrl(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().
        if (this.httpCodec != null && calls > 1) {
            throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
                    + " must call proceed() exactly once");
        }

        // 重新構(gòu)建一個RealInterceptorChain,將下標(biāo)增加
        okhttp3.internal.http.RealInterceptorChain next = new okhttp3.internal.http.RealInterceptorChain(
                interceptors, streamAllocation, httpCodec, connection, index + 1, request);
        Interceptor interceptor = interceptors.get(index); // 取出當(dāng)前角標(biāo)的攔截器
        Response response = interceptor.intercept(next); // 執(zhí)行攔截

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

        if (response == null) {
            throw new NullPointerException("interceptor " + interceptor + " returned null");
        }

        return response;
    }
}

5. 用戶自定義攔截器

我們可以自己添加一些攔截器進(jìn)行統(tǒng)一攔截處理,比如統(tǒng)一添加 token 或者 phone 等,也就是所謂的「AOP」.

自定義攔截器:

/**
 * 統(tǒng)一追加Header 參數(shù)
 */
public class AppendHeaderParamInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();


        Headers.Builder builder = request.
                headers().
                newBuilder();

        //統(tǒng)一追加header參數(shù)
        Headers newHeader = builder
                .add("token", getToken())
                .build();

        Request newRequest = request.newBuilder()
                .headers(newHeader)
                .build();


        return chain.proceed(newRequest);
    }
}

可以添加多個攔截器,操作也很簡單:

    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.addInterceptor(new AppendHeaderParamInterceptor());

6. 失敗重連攔截器

重試那些失敗或重定向的請求

/**
 * 重試那些失敗或重定向的請求
 */
public final class RetryAndFollowUpInterceptor implements Interceptor {
  /**
   * 重定向或授權(quán)執(zhí)行最大允許次數(shù)
   */
  private static final int MAX_FOLLOW_UPS = 20;

  private final OkHttpClient client;
  private final boolean forWebSocket;
  private StreamAllocation streamAllocation;
  private Object callStackTrace;
  private volatile boolean canceled;

  public RetryAndFollowUpInterceptor(OkHttpClient client, boolean forWebSocket) {
    this.client = client;
    this.forWebSocket = forWebSocket;
  }

  /**
   * 立即取消網(wǎng)絡(luò)請求(若此處持有該請求的話)
   */
  public void cancel() {
    canceled = true;
    StreamAllocation streamAllocation = this.streamAllocation;
    if (streamAllocation != null) streamAllocation.cancel();
  }

  public boolean isCanceled() {
    return canceled;
  }

  public void setCallStackTrace(Object callStackTrace) {
    this.callStackTrace = callStackTrace;
  }

  public StreamAllocation streamAllocation() {
    return streamAllocation;
  }

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

    streamAllocation = new StreamAllocation(
        client.connectionPool(), createAddress(request.url()), callStackTrace);

    int followUpCount = 0;
    Response priorResponse = null;
    while (true) {
      if (canceled) { // 已取消
        streamAllocation.release();
        throw new IOException("Canceled");
      }

      Response response = null;
      boolean releaseConnection = true;
      try {
        // 執(zhí)行請求
        response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null); 
        releaseConnection = false;
      } catch (RouteException e) {
        // route 通道連接失敗,請求將不會發(fā)出
        if (!recover(e.getLastConnectException(), false, request)) {
          throw e.getLastConnectException();
        }
        releaseConnection = false;
        continue;
      } catch (IOException e) {
        // 連接不到服務(wù)器
        boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
        if (!recover(e, requestSendStarted, request)) throw e;
        releaseConnection = false;
        continue;
      } finally {
        // 釋放資源
        if (releaseConnection) {
          streamAllocation.streamFailed(null);
          streamAllocation.release();
        }
      }

      // Attach the prior response if it exists. Such responses never have a body.
      if (priorResponse != null) {
        response = response.newBuilder()
            .priorResponse(priorResponse.newBuilder()
                    .body(null)
                    .build())
            .build();
      }

      Request followUp = followUpRequest(response);

      if (followUp == null) {
        if (!forWebSocket) {
          streamAllocation.release();
        }
        return response;
      }

      closeQuietly(response.body());

      // 超過了最大請求次數(shù)
      if (++followUpCount > MAX_FOLLOW_UPS) {
        streamAllocation.release();
        throw new ProtocolException("Too many follow-up requests: " + followUpCount);
      }

      // 讀不到的body
      if (followUp.body() instanceof 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()), callStackTrace);
      } 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;
    }
  }

  // 相當(dāng)于構(gòu)建一個完整的請求信息
  private Address createAddress(HttpUrl url) {
    SSLSocketFactory sslSocketFactory = null;
    HostnameVerifier hostnameVerifier = null;
    CertificatePinner certificatePinner = null;
    if (url.isHttps()) { // https的配置
      sslSocketFactory = client.sslSocketFactory();
      hostnameVerifier = client.hostnameVerifier();
      certificatePinner = client.certificatePinner();
    }

    return new Address(url.host(), url.port(), client.dns(), client.socketFactory(),
        sslSocketFactory, hostnameVerifier, certificatePinner, client.proxyAuthenticator(),
        client.proxy(), client.protocols(), client.connectionSpecs(), client.proxySelector());
  }

  /**
   * true則為可重連,不可重連為false
   */
  private boolean recover(IOException e, boolean requestSendStarted, Request userRequest) {
    streamAllocation.streamFailed(e);

    // application 層拒絕重連
    if (!client.retryOnConnectionFailure()) return false;

    // 不能重復(fù)發(fā)送請求
    if (requestSendStarted && userRequest.body() instanceof UnrepeatableRequestBody) return false;

    // 發(fā)生了致命錯誤不能重連
    if (!isRecoverable(e, requestSendStarted)) return false;

    // route不足
    if (!streamAllocation.hasMoreRoutes()) return false;
 
    return true;
  }

  // 判斷是否可恢復(fù)
  private boolean isRecoverable(IOException e, boolean requestSendStarted) {
    if (e instanceof ProtocolException) {
      return false;
    }

    if (e instanceof InterruptedIOException) {
      return e instanceof SocketTimeoutException && !requestSendStarted;
    }

    if (e instanceof SSLHandshakeException) {
      // 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;
    }

    return true;
  }

  /**
   * 縷清HTTP請求以返回響應(yīng). This will
   * either add authentication headers, follow redirects or handle a client request timeout. If a
   * follow-up is either unnecessary or not applicable, this returns null.
   */
  private Request followUpRequest(Response userResponse) throws IOException {
    if (userResponse == null) throw new IllegalStateException();
    Connection connection = streamAllocation.connection();
    Route route = connection != null
        ? connection.route()
        : null;
    int responseCode = userResponse.code();

    final String method = userResponse.request().method();
    switch (responseCode) {
      case HTTP_PROXY_AUTH: // 設(shè)置代理
        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);

      case HTTP_UNAUTHORIZED:
        return client.authenticator().authenticate(route, userResponse);

      case HTTP_PERM_REDIRECT:
      case HTTP_TEMP_REDIRECT: // 重定向
        if (!method.equals("GET") && !method.equals("HEAD")) {
          return null;
        }
      case HTTP_MULT_CHOICE:
      case HTTP_MOVED_PERM:
      case HTTP_MOVED_TEMP:
      case HTTP_SEE_OTHER:
        // 判斷是否允許重定向?
        if (!client.followRedirects()) return null;

        String location = userResponse.header("Location");
        if (location == null) return null;
        HttpUrl url = userResponse.request().url().resolve(location);

        if (url == null) return null;

        if (!sameScheme && !client.followSslRedirects()) return null;

        // 大多數(shù)重定向都不包含請求體,所以會從新構(gòu)建請求體
        Request.Builder requestBuilder = userResponse.request().newBuilder();
        if (HttpMethod.permitsRequestBody(method)) {
          final boolean maintainBody = HttpMethod.redirectsWithBody(method);
          if (HttpMethod.redirectsToGet(method)) { // GET 請求不包含請求體
            requestBuilder.method("GET", null); 
          } else {
            // 構(gòu)建請求體(將之前的請求體添加到新的請求中)
            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");
          }
        }

        //移除authentication請求頭
        if (!sameConnection(userResponse, url)) {
          requestBuilder.removeHeader("Authorization");
        }

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

      case HTTP_CLIENT_TIMEOUT:
        // 請求超時
        if (userResponse.request().body() instanceof UnrepeatableRequestBody) {
          return null;
        }

        return userResponse.request();

      default:
        return null;
    }
  }

  // 判斷是否與HttpUrl為同一個請求
  private boolean sameConnection(Response response, HttpUrl followUp) {
    HttpUrl url = response.request().url();
    return url.host().equals(followUp.host())
        && url.port() == followUp.port()
        && url.scheme().equals(followUp.scheme());
  }
}

7. BridgeInterceptor

構(gòu)建一個更友好的請求頭/請求體 (更完整的請求頭/體)

/**
 * 構(gòu)建一個更友好的請求頭/請求體 (更完整的請求頭/體)
 */
public final class BridgeInterceptor implements Interceptor {
    private final CookieJar cookieJar;

    public BridgeInterceptor(CookieJar cookieJar) {
        this.cookieJar = cookieJar;
    }

    @Override public Response intercept(Chain chain) throws IOException {
        Request userRequest = chain.request();
        Request.Builder requestBuilder = userRequest.newBuilder();

        RequestBody body = userRequest.body();
        if (body != null) { // 構(gòu)建請求體
            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 傳輸,并構(gòu)建 gzip 請求頭
        boolean transparentGzip = false;
        if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
            transparentGzip = true;
            requestBuilder.header("Accept-Encoding", "gzip");
        }

        // 投建cookie
        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()); // 版本為:okhttp/3.8.1
        }

        Response networkResponse = chain.proceed(requestBuilder.build());

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

        Response.Builder responseBuilder = networkResponse.newBuilder()
                .request(userRequest);

        // 判斷是否為 gzip 傳輸
        if (transparentGzip
                && "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
                && HttpHeaders.hasBody(networkResponse)) {
            // 構(gòu)建 gzip 響應(yīng)體
            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();
    }

    /** 構(gòu)建 cookie 頭 */
    private String cookieHeader(List<Cookie> cookies) {
        StringBuilder cookieHeader = new StringBuilder();
        for (int i = 0, size = cookies.size(); i < size; i++) {
            if (i > 0) {
                cookieHeader.append("; ");
            }
            Cookie cookie = cookies.get(i);
            cookieHeader.append(cookie.name()).append('=').append(cookie.value());
        }
        return cookieHeader.toString();
    }
}

主要的職責(zé):

    1. 負(fù)責(zé)將用戶構(gòu)建的一個 Request 請求轉(zhuǎn)化為能夠進(jìn)行網(wǎng)絡(luò)訪問的請求掩幢。
    1. 將這個符合網(wǎng)絡(luò)請求的 request 進(jìn)行網(wǎng)絡(luò)請求免绿。

8. CacheInterceptor

CacheInterceptor 會根據(jù)是否有網(wǎng)絡(luò)和緩存策略提供緩存,網(wǎng)絡(luò)響應(yīng)后將響應(yīng)


/**
 * 根據(jù)請求拿到緩存和將響應(yīng)寫到緩存中.
 */
public final class CacheInterceptor implements Interceptor {
    final InternalCache cache;

    public CacheInterceptor(InternalCache cache) {
        this.cache = cache;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        // 得到 request 對應(yīng)緩存中的 response
        Response cacheCandidate = cache != null
                ? cache.get(chain.request())
                : null;

        long now = System.currentTimeMillis();

        CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
        Request networkRequest = strategy.networkRequest;
        Response cacheResponse = strategy.cacheResponse;

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

        // 不適用 關(guān)閉
        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.
        // 禁止使用網(wǎng)絡(luò)并且沒有緩存 返回504
        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();
        }

        // 禁止使用網(wǎng)絡(luò) 就沒有必要進(jìn)行下去了,直接使用緩存
        if (networkRequest == null) {
            return cacheResponse.newBuilder()
                    .cacheResponse(stripBody(cacheResponse))
                    .build();
        }

        Response networkResponse = null;
        try {
            // 交給下一個攔截器郭脂,返回 networkResponse
            networkResponse = chain.proceed(networkRequest);
        } finally {
            // 關(guān)閉資源
            if (networkResponse == null && cacheCandidate != null) {
                closeQuietly(cacheCandidate.body());
            }
        }

        // 同時存在緩存和網(wǎng)絡(luò)響應(yīng)的情況 ==> 整合后返回響應(yīng)
        if (cacheResponse != null) {
            if (networkResponse.code() == HTTP_NOT_MODIFIED) {
                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();

                // 合并請求頭后更新緩存
                cache.trackConditionalCacheHit();
                cache.update(cacheResponse, response);
                return response;
            } else {
                closeQuietly(cacheResponse.body());
            }
        }

        // 能執(zhí)行到此處說明緩存不可用,要使用網(wǎng)絡(luò)響應(yīng)
        Response response = networkResponse.newBuilder()
                .cacheResponse(stripBody(cacheResponse))
                .networkResponse(stripBody(networkResponse))
                .build();

        if (cache != null) {
            if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
                // 添加到緩存中
                CacheRequest cacheRequest = cache.put(response);
                return cacheWritingResponse(cacheRequest, response);
            }

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

        return response;
    }

    private static Response stripBody(Response response) {
        return response != null && response.body() != null
                ? response.newBuilder().body(null).build()
                : response;
    }

   
}

9 ConnectInterceptor

向目標(biāo)服務(wù)器開啟鏈接 和 開啟下一個攔截器

/** 向目標(biāo)服務(wù)器開啟鏈接 和 開啟下一個攔截器 */
public final class ConnectInterceptor implements Interceptor {
    public final OkHttpClient client;

    public ConnectInterceptor(OkHttpClient client) {
        this.client = client;
    }

    @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);
    }
}

10 .CallServerInterceptor

CallServerInterceptor 是最后一個攔截器,內(nèi)部主要是通過 HttpCodec 構(gòu)建一個響應(yīng)體.

/** 這是鏈中的最后一個攔截器.向服務(wù)器發(fā)起請求. */
public final class CallServerInterceptor implements Interceptor {
    private final boolean forWebSocket;

    public CallServerInterceptor(boolean forWebSocket) {
        this.forWebSocket = forWebSocket;
    }

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

        long sentRequestMillis = System.currentTimeMillis();
        httpCodec.writeRequestHeaders(request);

        Response.Builder responseBuilder = null;
        if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
            // If there's a "Expect: 100-continue" header on the request, wait for a "HTTP/1.1 100
            // Continue" response before transmitting the request body. If we don't get that, return what
            // we did get (such as a 4xx response) without ever transmitting the request body.
            if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
                httpCodec.flushRequest();
                responseBuilder = httpCodec.readResponseHeaders(true);
            }

            if (responseBuilder == null) {
                // Write the request body if the "Expect: 100-continue" expectation was met.
                Sink requestBodyOut = httpCodec.createRequestBody(request, request.body().contentLength());
                BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
                request.body().writeTo(bufferedRequestBody); // 寫到請求體中
                bufferedRequestBody.close();
            } else if (!connection.isMultiplexed()) {
                // If the "Expect: 100-continue" expectation wasn't met, prevent the HTTP/1 connection from
                // being reused. Otherwise we're still obligated to transmit the request body to leave the
                // connection in a consistent state.
                streamAllocation.noNewStreams();
            }
        }

        httpCodec.finishRequest(); // 結(jié)束請求階段并將管道中的數(shù)據(jù) Flush

        // 獲取響應(yīng)
        if (responseBuilder == null) {
            responseBuilder = httpCodec.readResponseHeaders(false);
        }

        // 構(gòu)建響應(yīng) (此處還未構(gòu)建響應(yīng)體)
        Response response = responseBuilder
                .request(request)
                .handshake(streamAllocation.connection().handshake())
                .sentRequestAtMillis(sentRequestMillis)
                .receivedResponseAtMillis(System.currentTimeMillis())
                .build();

        int code = response.code();
        if (forWebSocket && code == 101) {
            // 鏈接還在更新中,確保攔截器不會得到 空 的響應(yīng)體
            // Connection is upgrading, but we need to ensure interceptors see a non-null response body.
            response = response.newBuilder()
                    .body(Util.EMPTY_RESPONSE)
                    .build();
        } else {
            // 構(gòu)建響應(yīng)體
            response = response.newBuilder()
                    .body(httpCodec.openResponseBody(response))
                    .build();
        }

        if ("close".equalsIgnoreCase(response.request().header("Connection"))
                || "close".equalsIgnoreCase(response.header("Connection"))) {
            streamAllocation.noNewStreams();
        }

        if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
            throw new ProtocolException(
                    "HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
        }

        return response;
    }
}

再來看下總的一張流程圖就會清晰了:


okhttp源碼分析.png

到這里我們只是從發(fā)起請求到獲得響應(yīng)的過程,還有很多細(xì)節(jié)的地方需要我們慢慢學(xué)習(xí).

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末疾呻,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子怎憋,更是在濱河造成了極大的恐慌又碌,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件绊袋,死亡現(xiàn)場離奇詭異毕匀,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)癌别,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進(jìn)店門皂岔,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人展姐,你說我怎么就攤上這事躁垛。” “怎么了圾笨?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵教馆,是天一觀的道長。 經(jīng)常有香客問我擂达,道長土铺,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任板鬓,我火速辦了婚禮悲敷,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘俭令。我一直安慰自己后德,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布抄腔。 她就那樣靜靜地躺著探遵,像睡著了一般。 火紅的嫁衣襯著肌膚如雪妓柜。 梳的紋絲不亂的頭發(fā)上箱季,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天,我揣著相機(jī)與錄音棍掐,去河邊找鬼藏雏。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的掘殴。 我是一名探鬼主播赚瘦,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼奏寨!你這毒婦竟也來了起意?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤病瞳,失蹤者是張志新(化名)和其女友劉穎揽咕,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體套菜,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡亲善,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了逗柴。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蛹头。...
    茶點故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖戏溺,靈堂內(nèi)的尸體忽然破棺而出渣蜗,到底是詐尸還是另有隱情,我是刑警寧澤旷祸,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布耕拷,位于F島的核電站,受9級特大地震影響肋僧,放射性物質(zhì)發(fā)生泄漏斑胜。R本人自食惡果不足惜控淡,卻給世界環(huán)境...
    茶點故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一嫌吠、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧掺炭,春花似錦辫诅、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至者冤,卻和暖如春肤视,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背涉枫。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工邢滑, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人愿汰。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓困后,卻偏偏與公主長得像乐纸,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子摇予,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,843評論 2 354