OKHttp網路請求原理流程解析

Rx_Re發表於2019-03-27

1. Okhttp基本使用

初始化可以新增自定義的攔截器

OkHttpClient okHttpClient = new OkHttpClient.Builder()
              .connectTimeout(30, TimeUnit.SECONDS)
              .writeTimeout(30, TimeUnit.SECONDS)
              .readTimeout(30, TimeUnit.SECONDS)
              .addInterceptor(interceptorImpl).builder();//建立OKHttpClient的Builder
複製程式碼

基本使用

String url = "http://wwww.baidu.com";
final Request request = new Request.Builder()
        .url(url)
        .get()//預設就是GET請求,可以不寫
        .build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        Log.d(TAG, "onFailure: ");
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        Log.d(TAG, "onResponse: " + response.body().string());
    }
});
複製程式碼

一般的使用大致就是這樣的

2.從OkHttpClient建立開始入手分析

OkHttpClient.Builder()使用builder模式,使用者可以自定義相應的引數

開發一般會用到的是

  .connectTimeout(30, TimeUnit.SECONDS)
  .writeTimeout(30, TimeUnit.SECONDS)
  .readTimeout(30, TimeUnit.SECONDS)
  .addInterceptor(interceptorImpl)
複製程式碼

連線時間,寫時間,讀時間以及對應的Interceptor相關的攔截器

3.構建Request

Request用的也是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);
  }
複製程式碼

tag主要是做標識的,請求返回為null時候的標識操作

4.構建Call

構建Call,主要是呼叫RealCall.newRealCall方法,並在其內部新增了一個事件回撥監聽

/**
   * Prepares the {@code request} to be executed at some point in the future.
   */
  @Override public Call newCall(Request request) {
    return RealCall.newRealCall(this, request, false /* for web socket */);
  }
  
  //RealCall
  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;
  }
  
複製程式碼

而在newRealCall方法中同時也呼叫了RealCall的構造方法 構造方法中加入了RetryAndFollowUpInterceptor重試攔截器,okhttp中加入了很多攔截器,這也是一大特色

 private RealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
    this.client = client;
    this.originalRequest = originalRequest;
    this.forWebSocket = forWebSocket;
    this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client, forWebSocket);
  }
複製程式碼

5. 執行非同步請求enqueue

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

executed以及synchronized主要是用來防止重複操作和多執行緒同步用的

接下來的方法

private void captureCallStackTrace() {
    Object callStackTrace = Platform.get().getStackTraceForCloseable("response.body().close()");
    retryAndFollowUpInterceptor.setCallStackTrace(callStackTrace);
  }
複製程式碼

重試監聽器做一些棧StackTrace記錄,以及eventListener.callStart(this);事件監聽做回撥處理,不影響流程

接著就到了Dispatcher的enqueue方法

 /** 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<>();

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

Dispatcher中定義三個佇列分別是readyAsyncCalls非同步等待,同步執行runningAsyncCalls以及runningSyncCalls非同步執行佇列,enqueue方法中,當執行非同步佇列個數小於最大請求數(64)並且同一Host請求個數小於maxRequestsPerHost(5)則加入非同步執行佇列,並且用執行緒執行,否則加入非同步等待佇列中,這是okhttp的執行緒佇列優化

6.檢視AsyncCall的run方法

AsyncCall 繼承了NamedRunnable,其內部會run方法會呼叫execute(),程式碼如下

 @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 {
          eventListener.callFailed(RealCall.this, e);
          responseCallback.onFailure(RealCall.this, e);
        }
      } finally {
        client.dispatcher().finished(this);
      }
    }
  }
複製程式碼

signalledCallback這個標識用來處理是否列印對應的日誌,這裡可以看到Response類,說明網路請求是在getResponseWithInterceptorChain中完成的,之後會回撥當前的Call狀態值

7.真正的網路請求的getResponseWithInterceptorChain

Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List<Interceptor> interceptors = new ArrayList<>();
    interceptors.addAll(client.interceptors());
    //失敗重試攔截器
    interceptors.add(retryAndFollowUpInterceptor);
    //request和response攔截器
    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));

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

    return chain.proceed(originalRequest);
  }
複製程式碼

加入各式各樣的攔截器,各個攔截器之間不耦合,易於使用者的自己配置,最後呼叫RealInterceptorChain的proceed方法

8.RealInterceptorChain的proceed方法

public RealInterceptorChain(List<Interceptor> interceptors, StreamAllocation streamAllocation,
      HttpCodec httpCodec, RealConnection connection, int index, Request request, Call call,
      EventListener eventListener, int connectTimeout, int readTimeout, int writeTimeout) {
    this.interceptors = interceptors;
    this.connection = connection;
    this.streamAllocation = streamAllocation;
    this.httpCodec = httpCodec;
    this.index = index;
    this.request = request;
    this.call = call;
    this.eventListener = eventListener;
    this.connectTimeout = connectTimeout;
    this.readTimeout = readTimeout;
    this.writeTimeout = writeTimeout;
  }
  
  public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
      RealConnection connection) throws IOException {
    if (index >= interceptors.size()) throw new AssertionError();

    calls++;

    //...

    // Call the next interceptor in the chain.
    RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
        connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
        writeTimeout);
    Interceptor interceptor = interceptors.get(index);
    Response response = interceptor.intercept(next);

    // .....

    return response;
  }
複製程式碼

構造方法中加入了eventListener事件監聽,看來okhttp中eventListener的監聽一直延伸到這裡,還加入了

    this.connectTimeout = connectTimeout;
    this.readTimeout = readTimeout;
    this.writeTimeout = writeTimeout;
複製程式碼

連線時間的配置

要重點關注的是index這個欄位,前面傳進來的時候,預設是0,而在proceed方法中,又重新執行了RealInterceptorChain的構造方法,並通過 interceptors.get(index)獲取下一個攔截器,並且執行interceptor.intercept(next)方法,隨便找一個攔截器看看

public final class BridgeInterceptor implements Interceptor {

  @Override public Response intercept(Chain chain) throws IOException {
    //省略部分程式碼
    Response networkResponse = chain.proceed(requestBuilder.build());
    //省略部分程式碼
    return responseBuilder.build();
  }
}
複製程式碼

攔截器內部又重新呼叫了chain.proceed的方法,這和遞迴操作類似,也是okHttp最經典的責任鏈模式。

9.同步操作

 @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);
    }
  }
複製程式碼

同步請求也是通過getResponseWithInterceptorChain來完成的,流程更簡單

10.大致的流程圖

image

相關文章