Okhttp源碼分析

版本號:3.13.1

一.基本使用

//1.創(chuàng)建OkHttpClient對象
val okHttpClient = OkHttpClient.Builder().readTimeout(5,TimeUnit.SECONDS).build()
//2.創(chuàng)建Request對象
val request = Request.Builder().url("www.baidu.com").build()
//3.通過OkHttpClient將Request封裝成Call對象
val call = okHttpClient.newCall(request)
//通過Call執(zhí)行請求
//同步請求
val response = call.execute()
Log.d("okhttp",response.body().toString())
//異步請求
call.enqueue(object :Callback{
    override fun onFailure(call: Call, e: IOException) {
    }

    override fun onResponse(call: Call, response: Response) {
        Log.d("okhttp",response.body().toString())
    }
})

Call可以理解為RequestResponse之間的橋梁怪与,Http請求過程中可能有重定向和重試等操作议泵,你的一個簡單請求可能會產(chǎn)生多個請求和響應(yīng)伊履。OkHttp使用Call這一概念對此來建模:不論為了滿足你的請求任務(wù)蓖宦,中間做了多少次請求和響應(yīng)宵呛,都算作一個Call篙悯。

二.源碼分析

1.創(chuàng)建對象源碼分析

不管是同步請求還是異步請求蚁阳,都必須先創(chuàng)建OkHttpClientRequest對象,上面使用Build模式創(chuàng)建的鸽照,下面分別看一下各自的源碼:

OkHttpClient.Builder().

public Builder() {
  //任務(wù)分發(fā)器
  dispatcher = new Dispatcher();
  protocols = DEFAULT_PROTOCOLS;
  connectionSpecs = DEFAULT_CONNECTION_SPECS;
  eventListenerFactory = EventListener.factory(EventListener.NONE);
  proxySelector = ProxySelector.getDefault();
  if (proxySelector == null) {
    proxySelector = new NullProxySelector();
  }
  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;
  callTimeout = 0;
  //java7以后在數(shù)字中可以使用下劃線螺捐,只是增加閱讀性,沒其他作用
  connectTimeout = 10_000;
  readTimeout = 10_000;
  writeTimeout = 10_000;
  pingInterval = 0;
}

Request.Builder()

public Builder() {
  this.method = "GET";
  this.headers = new Headers.Builder();
}

build()方法矮燎,都是在該方法中創(chuàng)建各自的對象定血,在構(gòu)造方法中將當(dāng)前的build對象傳入,然后把對應(yīng)的屬性值賦诞外。下面以Request為例:

public Request build() {
  if (url == null) throw new IllegalStateException("url == null");
  return new Request(this);
}
//Builder模式
Request(Builder builder) {
this.url = builder.url;
this.method = builder.method;
this.headers = builder.headers.build();
this.body = builder.body;
this.tags = Util.immutableMap(builder.tags);
}

不管同步請求還是異步請求澜沟,都是調(diào)用Call的方法執(zhí)行的,下面看一下Call對象的創(chuàng)建okHttpClient.newCall(request)

@Override public Call newCall(Request request) {
    //Call是一個接口峡谊,RealCall是它的實現(xiàn)類
    return RealCall.newRealCall(this, request, false /* for web socket */);
}

static RealCall newRealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
    // Safely publish the Call instance to the EventListener.
    //創(chuàng)建RealCall對象茫虽,將client和request傳入
    RealCall call = new RealCall(client, originalRequest, forWebSocket);
    //設(shè)置監(jiān)聽器
    call.eventListener = client.eventListenerFactory().create(call);
    return call;
}

private RealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
    this.client = client;
    this.originalRequest = originalRequest;
    this.forWebSocket = forWebSocket;
    //重定向攔截器
    this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client);
    this.timeout = new AsyncTimeout() {
        @Override protected void timedOut() {
         cancel();
        }
    };
    this.timeout.timeout(client.callTimeoutMillis(), MILLISECONDS);
}

從上面代碼中可以看到Call的實現(xiàn)類為RealCall,它持有clientrequest既们。

上面創(chuàng)建對象的源碼已經(jīng)分析完了濒析,下面就看一下具體請求的方法。

2.同步請求:call.execute()

@Override public Response execute() throws IOException {
    synchronized (this) {
      //同一個請求執(zhí)行執(zhí)行一遍啥纸,否則跑出異常
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    ......
    //當(dāng)執(zhí)行的請求開始的時候号杏,回調(diào)監(jiān)聽中的方法
    eventListener.callStart(this);
    try {
      //真正的請求是dispatcher.executed
      client.dispatcher().executed(this);
      Response result = getResponseWithInterceptorChain();
      if (result == null) throw new IOException("Canceled");
      return result;
    }......
   finally {
     //執(zhí)行完成以后從對列中移除請求
      client.dispatcher().finished(this);
    }
}

public Dispatcher dispatcher() {
   return dispatcher;
}

//dispatcher.executed
synchronized void executed(RealCall call) {
    //將call加入到同步請求對列中
    runningSyncCalls.add(call);
}

public final class Dispatcher {
  ......
  //異步就緒對列
  private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();
  //異步執(zhí)行對列
  private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();
  //同步執(zhí)行對列
  private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();
  ......
}

同步請求調(diào)用realCall.executed方法,在該方法中調(diào)用dispatcher.executedrealCall添加到同步運行對列中runningSyncCalls然后調(diào)用getResponseWithInterceptorChain獲取響應(yīng)報文斯棒。

3.異步請求: call.enqueue

@Override public void enqueue(Callback responseCallback) {
    synchronized (this) {
      //當(dāng)前的call(創(chuàng)建的call)只能執(zhí)行一次
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
    captureCallStackTrace();
    eventListener.callStart(this);
    //封裝成了AsyncCall馒索,它就是一個Runable
    client.dispatcher().enqueue(new AsyncCall(responseCallback));
}
void enqueue(AsyncCall call) {
    synchronized (this) {
      //添加到就緒對列
      readyAsyncCalls.add(call);
      ......
      }
    }
    promoteAndExecute();
}

private boolean promoteAndExecute() {
    assert (!Thread.holdsLock(this));
    List<AsyncCall> executableCalls = new ArrayList<>();
    boolean isRunning;
    synchronized (this) {
      //遍歷就緒對列執(zhí)行任務(wù)
      for (Iterator<AsyncCall> i = readyAsyncCalls.iterator(); i.hasNext(); ) {
        AsyncCall asyncCall = i.next();
        //如果請求大于最大的請求數(shù) maxRequests = 64,不執(zhí)行
        if (runningAsyncCalls.size() >= maxRequests) break; // Max capacity.
        //請求的host不能大于maxRequestsPerHost = 5
        if (asyncCall.callsPerHost().get() >= maxRequestsPerHost) continue; // Host max capacity.
        i.remove();
        asyncCall.callsPerHost().incrementAndGet();
        //沒有大于最大請求數(shù)名船,添加到執(zhí)行對列中
        executableCalls.add(asyncCall);
        runningAsyncCalls.add(asyncCall);
      }
      isRunning = runningCallsCount() > 0;
    }
    //循環(huán)執(zhí)行對列,執(zhí)行具體的請求
    for (int i = 0, size = executableCalls.size(); i < size; i++) {
      AsyncCall asyncCall = executableCalls.get(i);
      //執(zhí)行任務(wù)旨怠,傳入線程池
      asyncCall.executeOn(executorService());
    }
    return isRunning;
}

異步請求的時候渠驼,通過dispatcher.enqueue方法將call(封裝成了Runable(AsyncCall,它是RealCall的的內(nèi)部類))添加到就緒對列中,然后循環(huán)就緒對列鉴腻,如果現(xiàn)在執(zhí)行的任務(wù)數(shù)沒有超過最大的請求數(shù)(64)就添加到執(zhí)行對列中迷扇,然后執(zhí)行asyncCall.executeOn(executorService());百揭。

public synchronized ExecutorService executorService() {
    if (executorService == null) {
     //最大的線程數(shù)為 Integer.MAX_VALUE,上面已經(jīng)限制最大的請求數(shù)為64所以這里的數(shù)量不會超過64
      executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
          new SynchronousQueue<>(), Util.threadFactory("OkHttp Dispatcher", false));
    }
    return executorService;
}

void executeOn(ExecutorService executorService) {
  assert (!Thread.holdsLock(client.dispatcher()));
  boolean success = false;
  try {
    //執(zhí)行任務(wù)
    executorService.execute(this);
    success = true;
  } catch (RejectedExecutionException e) {
    InterruptedIOException ioException = new InterruptedIOException("executor rejected");
    ioException.initCause(e);
    eventListener.callFailed(RealCall.this, ioException);
    responseCallback.onFailure(RealCall.this, ioException);
  } finally {
    if (!success) {
      client.dispatcher().finished(this); // This call is no longer running!
    }
  }
}

executorService.execute(this);就是執(zhí)行AsyncCall中的run()方法

AsyncCall繼承NamedRunnable蜓席,沒有重寫run()方法器一,直接調(diào)用父類的,在父類的run()方法中調(diào)用了一個execute();方法厨内,該方法是一個抽象方法祈秕,需要子類實現(xiàn),所以實際執(zhí)行的是AsyncCall.execute()

public abstract class NamedRunnable implements Runnable {
  ......
  @Override public final void run() {
    String oldName = Thread.currentThread().getName();
    Thread.currentThread().setName(name);
    try {
      execute();
    } finally {
      Thread.currentThread().setName(oldName);
    }
  }
  protected abstract void execute();
}

下面就看一個AsyncCall.execute()雏胃,真正執(zhí)行任務(wù)的方法:

//該方法在子線程中執(zhí)行
@Override protected void execute() {
      boolean signalledCallback = false;
      timeout.enter();
      try {
        //獲取響應(yīng)報文
        Response response = getResponseWithInterceptorChain();
        if (retryAndFollowUpInterceptor.isCanceled()) {
          signalledCallback = true;
          responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
        } else {
          signalledCallback = true;
          responseCallback.onResponse(RealCall.this, response);
        }
      }......
      finally {
        //調(diào)用finished方法请毛,將該請求從請求對列中移除
        client.dispatcher().finished(this);
      }
    }
}

從上面的代碼分析我們可以得出:異步請求流程call.enqueue->realCall.enqueue->dispatcher.enqueue(AsyncCall call)(AsyncCall本質(zhì)就是一個Runable)在dispatcher.enqueue方法中將call添加到就緒對列中,然后外遍歷就緒對列瞭亮,如果現(xiàn)在運行的任務(wù)沒有超過最大請求數(shù)(64)就會把它加入到運行對列中runningAsyncCalls方仿,然后調(diào)用asyncCall.executeOn(executorService())(executorService()方法就是創(chuàng)建一個線程池),在executeOn方法中會執(zhí)行asyncCall统翩,就是調(diào)用它的execute方法仙蚜。在該方法中真正的去執(zhí)行任務(wù),該方法是在子線程中執(zhí)行的厂汗。

通過上面的分析我們可以得出大致的請求流程圖如下:

請求流程圖

不管是同步請求還是異步請求委粉,都調(diào)用了dispatcher對應(yīng)的方法,它里面維護(hù)了三個任務(wù)對列和一個線程池(用來執(zhí)行異步請求)面徽,dispatcher維護(hù)著請求任務(wù)的添加和移除艳丛。

三.Okhttp中的攔截器

攔截器Okhttp提供的一種強大的機制,它可以實現(xiàn)網(wǎng)絡(luò)監(jiān)聽趟紊、請求以及響應(yīng)重寫氮双、請求失敗重試等功能。

Okhttp攔截器分為兩種:一種是應(yīng)用攔截器(就是我們自定義的攔截器)霎匈,另一種就是網(wǎng)絡(luò)攔截器(是Okhttp內(nèi)部提供給我們的攔截器戴差,真正的網(wǎng)絡(luò)請求就是通過這些網(wǎng)絡(luò)攔截器來實現(xiàn)的)。

從上面的代碼分析得出:不管是同步請求還是異步請求铛嘱,最終都是通過getResponseWithInterceptorChain()方法來獲取Response的暖释,該方法就是構(gòu)建一個攔截器鏈。下面看一下該方法的代碼:

//RealCall中的方法
Response getResponseWithInterceptorChain() throws IOException {
    List<Interceptor> interceptors = new ArrayList<>();
    //添加自定義的攔截器
    interceptors.addAll(client.interceptors());
    //添加okhttp提供給我們的網(wǎng)絡(luò)攔截器
    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());
    }
    interceptors.add(new CallServerInterceptor(forWebSocket));
    //創(chuàng)建一個攔截器鏈對象墨吓,然后將攔截器集合傳入
    Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
        originalRequest, this, eventListener, client.connectTimeoutMillis(),
        client.readTimeoutMillis(), client.writeTimeoutMillis());
    return chain.proceed(originalRequest);
}

創(chuàng)建好攔截器鏈以后調(diào)用了該對象的chain.proceed(originalRequest)方法球匕。該方法源碼如下:

public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
  RealConnection connection) throws IOException {
    ......
    //又創(chuàng)建了一個攔截器鏈對象,注意此時傳入的index = index + 1
    RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
        connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
        writeTimeout);
    //順序獲取攔截器帖烘,然后調(diào)用攔截器的intercept方法
    Interceptor interceptor = interceptors.get(index);
    Response response = interceptor.intercept(next);
    ......
    return response;
}

chain.proceed方法中調(diào)用了interceptor.intercept(next);方法亮曹,并將新創(chuàng)建的攔截器鏈對象傳入,此時index為index + 1,這樣就構(gòu)成了依次調(diào)用攔截器集合的所用攔截器的intercept方法照卦。在該方法中完成對應(yīng)的功能以后式矫,調(diào)用下一個攔截器的intercept方法,并將處理后的Response返回給上一個攔截器役耕。

攔截器處理流程圖

1.RetryAndFollowUpInterceptor(重定向攔截器)

該攔截器的主要作用就是:負(fù)責(zé)請求的重定向操作以及請求失敗后的重試機制采转。

@Override public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Call call = realChain.call();
    EventListener eventListener = realChain.eventListener();
    //1.創(chuàng)建StreamAllocation 對象,該對象用于分配請求過程中的流
    StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
        createAddress(request.url()), call, eventListener, callStackTrace);
    this.streamAllocation = streamAllocation;
    //重連次數(shù)
    int followUpCount = 0;
    Response priorResponse = null;
    while (true) {
      ......
      Response response;
      boolean releaseConnection = true;
      try {
        //2.調(diào)用RealInterceptorChain的proceed方法進(jìn)行網(wǎng)絡(luò)請求
        response = realChain.proceed(request, streamAllocation, null, null);
        releaseConnection = false;
      }......
      // 疊加先前的響應(yīng)
      if (priorResponse != null) {
        response = response.newBuilder()
            .priorResponse(priorResponse.newBuilder()
                    .body(null)
                    .build())
            .build();
      }
      Request followUp;
      try {
        //根據(jù)響應(yīng)判斷是否需要重新請求
        followUp = followUpRequest(response, streamAllocation.route());
      }......
      if (followUp == null) {
        //不需要重新請求瞬痘,直接返回response故慈,結(jié)束while循環(huán)
        streamAllocation.release(true);
        return response;
      }
      ......
      //需要重新請求,先判斷重新請求的次數(shù)是否超過設(shè)置的最大值图云,MAX_FOLLOW_UPS = 20
      if (++followUpCount > MAX_FOLLOW_UPS) {
        //超過最大的重新請求次數(shù)惯悠,拋出異常
        streamAllocation.release(true);
        throw new ProtocolException("Too many follow-up requests: " + followUpCount);
      }
      ......
     //重新請求
     if (!sameConnection(response, followUp.url())) {
        streamAllocation.release(false);
        streamAllocation = new StreamAllocation(client.connectionPool(),
            createAddress(followUp.url()), call, eventListener, callStackTrace);
        this.streamAllocation = streamAllocation;
      }......
      request = followUp;
      priorResponse = response;
    }
}

RetryAndFollowUpInterceptor.intercept方法得出主要做了以下幾件事:

  • 1.創(chuàng)建StreamAllocation對象。
  • 2.調(diào)用RealInterceptorChainproceed方法進(jìn)行網(wǎng)絡(luò)請求竣况,該方法就會調(diào)用下一個攔截器intercept方法克婶,依次調(diào)用,獲取對應(yīng)的Response丹泉。

intercept方法有些類似遞歸調(diào)用情萤,這里是不同攔截器對象的intercept方法,這樣就從上到下形成了一個鏈摹恨。

  • 3.根據(jù)異常結(jié)果或者響應(yīng)結(jié)果判斷是否要進(jìn)行重新請求筋岛。

2.BridgeInterceptor(橋接攔截器)

該攔截器的作用主要就是處理請求和響應(yīng)

RetryAndFollowUpInterceptor攔截器中創(chuàng)建StreamAllocation對象以后,就會調(diào)用chain.proceed方法進(jìn)行網(wǎng)絡(luò)請求晒哄,其實就是調(diào)用下一個攔截器的intercept方法睁宰,RetryAndFollowUpInterceptor的下一個攔截就是BridgeInterceptor,下面看一下它的intercept代碼:

@Override public Response intercept(Chain chain) throws IOException {
    Request userRequest = chain.request();
    Request.Builder requestBuilder = userRequest.newBuilder();
    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.
    boolean transparentGzip = false;
    if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == 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());
    }
    //2.發(fā)送網(wǎng)絡(luò)請求
    Response networkResponse = chain.proceed(requestBuilder.build());
    //3.解壓響應(yīng)數(shù)據(jù)寝凌,支持`gzip`柒傻,所以需要解壓
    HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
    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);
      String contentType = networkResponse.header("Content-Type");
      responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
    }

    return responseBuilder.build();
}

BridgeInterceptor.intercept方法得出主要做了以下幾件事:

  • 1.將用戶構(gòu)建的Request轉(zhuǎn)化為能夠進(jìn)行網(wǎng)絡(luò)訪問的請求(添加一些頭信息,如:Connection较木、Accept-Encoding红符、Host等)。
  • 2.將設(shè)置好的Request發(fā)送網(wǎng)絡(luò)請求(調(diào)用chan.proceed)伐债。
  • 3.將請求返回的Response轉(zhuǎn)化為用戶可用的Response(可能使用gzip壓縮预侯,需要解壓)。

3.CacheInterceptor(緩存攔截器)

該攔截器的作用主要就是處理數(shù)據(jù)的緩存

BridgeInterceptor.intercept方法中構(gòu)建好Request后就發(fā)送請求峰锁,就會調(diào)用CacheInterceptor.intercept方法萎馅,該方法的代碼為:

@Override public Response intercept(Chain chain) throws IOException {
    //如果設(shè)置了緩存就獲取緩存
    Response cacheCandidate = cache != null
        ? cache.get(chain.request())
        : null;

    long now = System.currentTimeMillis();
    //獲取緩存策略,里面維護(hù)著一個networkRequest和cacheResponse
    CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
    Request networkRequest = strategy.networkRequest;
    Response cacheResponse = strategy.cacheResponse;
    if (cache != null) {
      //如果有緩存虹蒋,跟新一下緩存的各項指標(biāo)校坑,主要是緩存命中率
      cache.trackResponse(strategy);
    }
    if (cacheCandidate != null && cacheResponse == null) {
      //有緩存拣技,但是對應(yīng)的Response 為null即緩存不符合要求,關(guān)閉該緩存
      closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
    }

    // 如果此時網(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ò)不可用徐绑,但是有緩存邪驮,直接返回緩存。
    if (networkRequest == null) {
      return cacheResponse.newBuilder()
          .cacheResponse(stripBody(cacheResponse))
          .build();
    }
    //沒有緩存傲茄,但是網(wǎng)路可用毅访,發(fā)起網(wǎng)絡(luò)請求
    Response networkResponse = null;
    try {
      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 (cacheResponse != null) {
      //如果網(wǎng)絡(luò)請求返回的狀態(tài)碼為 HTTP_NOT_MODIFIED = 304,從緩存中獲取數(shù)據(jù)
      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();
        ......
    }

    Response response = networkResponse.newBuilder()
        .cacheResponse(stripBody(cacheResponse))
        .networkResponse(stripBody(networkResponse))
        .build();

    if (cache != null) {
      //如果請求可以緩存盘榨,就將網(wǎng)絡(luò)請求后的數(shù)據(jù)添加到緩存
      if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
        // Offer this request to the cache.
        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;
}

從上面代碼可以得出CacheInterceptor的處理邏輯為:

  • 1.如果網(wǎng)絡(luò)不可用,同時沒有緩存草巡,會返回一個504的響應(yīng)碼守呜。
  • 2.如果網(wǎng)絡(luò)不可用,但是有緩存山憨,直接返回緩存的數(shù)據(jù)查乒。
  • 3.如果網(wǎng)絡(luò)可用,發(fā)送網(wǎng)絡(luò)請求(調(diào)用chain.proceed)郁竟。
    • 如果有緩存并且網(wǎng)絡(luò)請求返回的狀態(tài)碼為 HTTP_NOT_MODIFIED = 304玛迄,就從緩存中獲取數(shù)據(jù)。
    • 如果沒有緩存蓖议,就返回網(wǎng)絡(luò)請求的數(shù)據(jù)讥蟆。此時如果設(shè)置了緩存,就將網(wǎng)絡(luò)請求后的數(shù)據(jù)添加到緩存中(cache.put(response)

緩存的管理使用的Cache類中響應(yīng)的方法(get攻询、put),我們先看一下怎么使用緩存:

val okHttpClient = OkHttpClient.Builder()
              .readTimeout(5,TimeUnit.SECONDS)
              .cache(Cache(File("cache"),24 * 1024 * 1024))//通過配置Cache對象
              .build()

下面我們就看一下Cache這個類的源碼:

@Nullable CacheRequest put(Response response) {
    String requestMethod = response.request().method();

    if (HttpMethod.invalidatesCache(response.request().method())) {
      try {
        remove(response.request());
      } catch (IOException ignored) {
        // The cache cannot be written.
      }
      return null;
    }
    //只緩存GET請求
    if (!requestMethod.equals("GET")) {
      return null;
    }
    //Vary的內(nèi)容會作為當(dāng)前緩存數(shù)據(jù)是否可以作為請求結(jié)果返回給客戶端的判斷
    //Vary詳解:https://blog.csdn.net/qq_29405933/article/details/84315254
    if (HttpHeaders.hasVaryAll(response)) {
      return null;
    }
    //緩存數(shù)據(jù)的實體對象
    Entry entry = new Entry(response);
    //使用磁盤緩存DiskLruCache來實現(xiàn)緩存功能
    DiskLruCache.Editor editor = null;
    try {
      editor = cache.edit(key(response.request().url()));
      if (editor == null) {
        return null;
      }
      entry.writeTo(editor);
      return new CacheRequestImpl(editor);
    }......
}

從上述代碼可以看出Okhttp中的緩存使用的是DiskLruCache钧栖。

4.ConnectInterceptor(連接攔截器)

該攔截器的作用主要就是建立與服務(wù)器的連接(Socket)

如果沒有緩存低零,但是網(wǎng)絡(luò)可用的情況下就會調(diào)用ConnectInterceptor.intercept方法,下面看一下該方法的代碼:

@Override public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Request request = realChain.request();
    //獲取StreamAllocation對象拯杠,該對象是在RetryAndFollowUpInterceptor中實例化的
    StreamAllocation streamAllocation = realChain.streamAllocation();
    // We need the network to satisfy this request. Possibly for validating a conditional GET.
    boolean doExtensiveHealthChecks = !request.method().equals("GET");
    //創(chuàng)建HttpCodec對象潭陪,該對象用于請求和響應(yīng)的處理
    HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);
    //創(chuàng)建用于網(wǎng)絡(luò)IO的RealConnection對象
    RealConnection connection = streamAllocation.connection();
    //調(diào)用后面攔截的intercept方法并傳遞對應(yīng)的參數(shù)老厌,發(fā)起網(wǎng)絡(luò)請求
    return realChain.proceed(request, streamAllocation, httpCodec, connection);
}

下面重點看一下streamAllocation.newStream方法:

public HttpCodec newStream(
  OkHttpClient client, Interceptor.Chain chain, boolean doExtensiveHealthChecks) {
    ......
    try {
      //獲取一個RealConnection對象
      RealConnection resultConnection = findHealthyConnection(connectTimeout, readTimeout,
          writeTimeout, pingIntervalMillis, connectionRetryEnabled, doExtensiveHealthChecks);
      //通過RealConnection對象創(chuàng)建HttpCodec對象
      HttpCodec resultCodec = resultConnection.newCodec(client, chain, this);
      synchronized (connectionPool) {
        codec = resultCodec;
        return resultCodec;
      }
    } catch (IOException e) {
      throw new RouteException(e);
    }
}

findHealthyConnection方法會調(diào)用findConnection方法來獲取一個RealConnection對象枝秤,代碼如下:

private RealConnection findConnection(int connectTimeout, int readTimeout, int writeTimeout,
  int pingIntervalMillis, boolean connectionRetryEnabled) throws IOException {
    ......
    synchronized (connectionPool) {
      ......
      if (this.connection != null) {
        //如果能復(fù)用就復(fù)用,this代表的是StreamAllocation對象
        result = this.connection;
        releasedConnection = null;
      }
      ......
    }
    ......
    不能復(fù)用從連接池中找
    synchronized (connectionPool) {
      if (canceled) throw new IOException("Canceled");
      if (newRouteSelection) {
        List<Route> routes = routeSelection.getAll();
        for (int i = 0, size = routes.size(); i < size; i++) {
          Route route = routes.get(i);
          Internal.instance.acquire(connectionPool, address, this, route);
          if (connection != null) {
            foundPooledConnection = true;
            result = connection;
            this.route = route;
            break;
          }
        }
      }
      if (!foundPooledConnection) {
        //連接池中沒有就new一個
        if (selectedRoute == null) {
          selectedRoute = routeSelection.next();
        }
        route = selectedRoute;
        refusedStreamCount = 0;
        result = new RealConnection(connectionPool, selectedRoute);
        acquire(result, false);
      }
    }
    ......
    開啟Socket連接
    result.connect(connectTimeout, readTimeout, writeTimeout, pingIntervalMillis,
        connectionRetryEnabled, call, eventListener);
    routeDatabase().connected(result.route());
    Socket socket = null;
    synchronized (connectionPool) {
      reportedAcquired = true;
      //connection將加入連接池中
      Internal.instance.put(connectionPool, result);
      ......
    }
    .......
    return result;
}

findConnection方法做的主要就是:

  • 1.如果StreamAllocation中的connection能復(fù)用就復(fù)用,不同復(fù)用的話就從連接池connectionPool中獲取菌赖,如果連接池中沒有就new一個琉用,然后加入連接池中辕羽。
  • 最終調(diào)用RealConnectionconnect方法打開一個socket鏈接

獲取resultConnection對象后然后調(diào)用resultConnection.newCodec來獲取HttpCodec 對象

public HttpCodec newCodec(OkHttpClient client, Interceptor.Chain chain,
  StreamAllocation streamAllocation) throws SocketException {
    if (http2Connection != null) {
      return new Http2Codec(client, chain, streamAllocation, http2Connection);
    } else {
      socket.setSoTimeout(chain.readTimeoutMillis());
      source.timeout().timeout(chain.readTimeoutMillis(), MILLISECONDS);
      sink.timeout().timeout(chain.writeTimeoutMillis(), MILLISECONDS);
      return new Http1Codec(client, streamAllocation, source, sink);
    }
}

創(chuàng)建好RealConnectionHttpCodec對象以后刁愿,調(diào)用下一個攔截器intercept方法铣口。下面我們最后一個攔截器:CallServerInterceptor

5.CallServerInterceptor(發(fā)起請求攔截器)

該攔截器的主要作用就是真正的向服務(wù)器寫入請求數(shù)據(jù)和讀取響應(yīng)數(shù)據(jù)

該攔截器為Okhttp攔截器鏈的最后一個攔截器脑题,該攔截器是真正向服務(wù)器發(fā)送請求和處理響應(yīng)的地方叔遂。下面看一下它的intercept方法代碼:

@Override public Response intercept(Chain chain) throws IOException {
    final RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Call call = realChain.call();
    final HttpCodec httpCodec = realChain.httpStream();
    StreamAllocation streamAllocation = realChain.streamAllocation();
    RealConnection connection = (RealConnection) realChain.connection();
    Request request = realChain.request();
    ......
    //向socket中寫入header數(shù)據(jù)
    httpCodec.writeRequestHeaders(request);
    ......
    Response.Builder responseBuilder = null;
    if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
      if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
        //如果請求頭中有配置“Expect: 100-continue” 已艰,直接讀取響應(yīng)頭信息
        httpCodec.flushRequest();
        realChain.eventListener().responseHeadersStart(call);
        responseBuilder = httpCodec.readResponseHeaders(true);
      }

      if (responseBuilder == null) {
        if (request.body() instanceof DuplexRequestBody) {
          httpCodec.flushRequest();
          CountingSink requestBodyOut = new CountingSink(httpCodec.createRequestBody(request, -1L));
          BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
          //向socket寫入請求體
          request.body().writeTo(bufferedRequestBody);
        } else {
          // Write the request body if the "Expect: 100-continue" expectation was met.
          realChain.eventListener().requestBodyStart(call);
          long contentLength = request.body().contentLength();
          CountingSink requestBodyOut =
              new CountingSink(httpCodec.createRequestBody(request, contentLength));
          BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);

          request.body().writeTo(bufferedRequestBody);
          bufferedRequestBody.close();
          realChain.eventListener().requestBodyEnd(call, requestBodyOut.successfulCount);
        }
      }
      ......
    }

    if (!(request.body() instanceof DuplexRequestBody)) {
      //結(jié)束請求
      httpCodec.finishRequest();
    }

    //讀取響應(yīng)信息
    if (responseBuilder == null) {
      realChain.eventListener().responseHeadersStart(call);
      responseBuilder = httpCodec.readResponseHeaders(false);
    }

    responseBuilder
        .request(request)
        .handshake(streamAllocation.connection().handshake())
        .sentRequestAtMillis(sentRequestMillis)
        .receivedResponseAtMillis(System.currentTimeMillis());
    Internal.instance.initCodec(responseBuilder, httpCodec);
    Response response = responseBuilder.build();

    int code = response.code();
    if (code == 100) {
      // server sent a 100-continue even though we did not request one.
      // try again to read the actual response
      responseBuilder = httpCodec.readResponseHeaders(false);

      responseBuilder
          .request(request)
          .handshake(streamAllocation.connection().handshake())
          .sentRequestAtMillis(sentRequestMillis)
          .receivedResponseAtMillis(System.currentTimeMillis());
      Internal.instance.initCodec(responseBuilder, httpCodec);
      response = responseBuilder.build();
      code = response.code();
    }

    realChain.eventListener().responseHeadersEnd(call, response);

    if (forWebSocket && code == 101) {
      response = response.newBuilder()
          .body(Util.EMPTY_RESPONSE)
          .build();
    } else {
      //回去響應(yīng)體數(shù)據(jù)
      response = response.newBuilder()
          .body(httpCodec.openResponseBody(response))
          .build();
    }
    ......
    return response;
}

從上面代碼可以看出CallServerInterceptor主要就是向Socket中寫入請求信息涩笤,然后讀取響應(yīng)信息盒件,最后構(gòu)建Response對象并返回給上一個攔截器炒刁。

總結(jié)

至此Okhttp的關(guān)鍵代碼已經(jīng)分析完畢切心,我們可以得出Okhttp的一次請求過程大概是:

  • 1.將請求封裝成Call對象
  • 2.通過Dispatcher對請求進(jìn)行分發(fā)协屡。
  • 3.調(diào)用RealCall對象的getResponseWithInterceptorChain方法獲取Response
  • 4.getResponseWithInterceptorChain方法中會依次調(diào)用攔截器:RetryAndFollowUpInterceptor肤晓、BridgeInterceptor补憾、CacheInterceptor盈匾、ConnectInterceptor、CallServerInterceptorintercept方法岩瘦,完成對于請求信息的封裝启昧,發(fā)送和讀取密末。

Kotlin項目實戰(zhàn)

網(wǎng)絡(luò)優(yōu)化

HTTPDNS使用HTTP協(xié)議進(jìn)行域名解析跛璧,代替現(xiàn)有基于UDP的DNS協(xié)議赡模,域名解析請求直接發(fā)送到阿里云的HTTPDNS服務(wù)器漓柑,從而繞過運營商的Local DNS,能夠避免Local DNS造成的域名劫持問題和調(diào)度不精準(zhǔn)問題瞬矩。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末涵叮,一起剝皮案震驚了整個濱河市伞插,隨后出現(xiàn)的幾起案子媚污,更是在濱河造成了極大的恐慌耗美,老刑警劉巖商架,帶你破解...
    沈念sama閱讀 212,383評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蛇摸,死亡現(xiàn)場離奇詭異,居然都是意外死亡诬烹,警方通過查閱死者的電腦和手機绞吁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,522評論 3 385
  • 文/潘曉璐 我一進(jìn)店門家破,熙熙樓的掌柜王于貴愁眉苦臉地迎上來汰聋,“玉大人烹困,你說我怎么就攤上這事乾吻。” “怎么了酝锅?”我有些...
    開封第一講書人閱讀 157,852評論 0 348
  • 文/不壞的土叔 我叫張陵搔扁,是天一觀的道長稿蹲。 經(jīng)常有香客問我场绿,道長嫉入,這世上最難降的妖魔是什么咒林? 我笑而不...
    開封第一講書人閱讀 56,621評論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮蛀序,結(jié)果婚禮上徐裸,老公的妹妹穿的比我還像新娘重贺。我一直安慰自己气笙,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 65,741評論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著堵第,像睡著了一般。 火紅的嫁衣襯著肌膚如雪型诚。 梳的紋絲不亂的頭發(fā)上狰贯,一...
    開封第一講書人閱讀 49,929評論 1 290
  • 那天傍妒,我揣著相機與錄音摸柄,去河邊找鬼驱负。 笑死跃脊,一個胖子當(dāng)著我的面吹牛酪术,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播橡疼,決...
    沈念sama閱讀 39,076評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼耻涛!你這毒婦竟也來了瘟檩?” 一聲冷哼從身側(cè)響起墨辛,我...
    開封第一講書人閱讀 37,803評論 0 268
  • 序言:老撾萬榮一對情侶失蹤奏赘,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后疲憋,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體缚柳,經(jīng)...
    沈念sama閱讀 44,265評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡秋忙,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,582評論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了弹澎。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片裁奇。...
    茶點故事閱讀 38,716評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖免胃,靈堂內(nèi)的尸體忽然破棺而出羔沙,到底是詐尸還是另有隱情扼雏,我是刑警寧澤夯膀,帶...
    沈念sama閱讀 34,395評論 4 333
  • 正文 年R本政府宣布蝴蜓,位于F島的核電站,受9級特大地震影響格仲,放射性物質(zhì)發(fā)生泄漏凯肋。R本人自食惡果不足惜侮东,卻給世界環(huán)境...
    茶點故事閱讀 40,039評論 3 316
  • 文/蒙蒙 一苗桂、第九天 我趴在偏房一處隱蔽的房頂上張望煤伟。 院中可真熱鬧便锨,春花似錦放案、人聲如沸吱殉。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,798評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽流礁。三九已至神帅,卻和暖如春枕稀,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背凹联。 一陣腳步聲響...
    開封第一講書人閱讀 32,027評論 1 266
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留瓜浸,地道東北人插佛。 一個月前我還...
    沈念sama閱讀 46,488評論 2 361
  • 正文 我出身青樓氢拥,卻偏偏與公主長得像嫩海,于是被迫代替她去往敵國和親叁怪。 傳聞我的和親對象是個殘疾皇子深滚,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,612評論 2 350

推薦閱讀更多精彩內(nèi)容

  • OkHttp源碼分析 在現(xiàn)在的Android開發(fā)中痴荐,請求網(wǎng)絡(luò)獲取數(shù)據(jù)基本上成了我們的標(biāo)配展箱。在早期的Android開...
    BlackFlag閱讀 324評論 0 5
  • 主目錄見:Android高級進(jìn)階知識(這是總目錄索引)?OkHttp的知識點實在是不少,優(yōu)秀的思想也有很多蹬昌,這里只...
    ZJ_Rocky閱讀 2,288評論 2 6
  • 那么我今天給大家簡單地講一下Okhttp這款網(wǎng)絡(luò)框架及其原理。它是如何請求數(shù)據(jù)攀隔,如何響應(yīng)數(shù)據(jù)的 有什么優(yōu)點皂贩?它的應(yīng)...
    卓而不群_0137閱讀 314評論 0 1
  • OkHttp源碼分析-同步篇 很早就想拿okhttp開刀了,這次就記一次使用OKhttp的網(wǎng)絡(luò)請求昆汹。首先需要說明的...
    埃賽爾閱讀 976評論 1 2
  • 我一直很好奇一個人在因為被打擾睡覺而發(fā)脾氣辈末,之后又是怎樣快速進(jìn)入睡眠狀態(tài)的。 我很難這樣,因為會糾結(jié)別人的想法挤聘。 ...
    翻手光陰覆手金閱讀 582評論 0 1