OKhttp源碼學習(三)—— Request, RealCall

Request,RealCall 分析

源碼地址:https://github.com/square/okhttp

上一篇 對okHttpClient做了簡單的分析,現在就對另外兩個比較重要的類進行學習分析(Request, RealCall),這兩個類是我們調用時候的請求相關的類。
這里做簡單的學習分析,便于后面流程的理解。

Request

Request這個請求類,同樣的使用了Bulider模式,不過這個比OkhttpClient簡單多了,主要用于添加請求需要的一些基本屬性。

        final HttpUrl url;
        final String method;
        final Headers headers;
        final RequestBody body;
        final Object tag;
      Request(Builder builder) {
        this.url = builder.url;
        this.method = builder.method;
        this.headers = builder.headers.build();
        this.body = builder.body;
        this.tag = builder.tag != null ? builder.tag : this;
    }
  1. url,傳入的String ,經過進一步加工處理,還有一些錯誤的判斷,最后轉換為HttpUrl的類。
  2. method,確定請求的類型,默認使用GET。支持http 基本的請求方式。
  3. headers, 我們可以自定義添加對應的Header , 最后轉換成Header類。也可以對其中的Header進行操作。
  4. body,請求的實體,RequestBody ,傳輸的contentType,把傳輸的content,進行簡單處理。
  5. tag,標簽。

RealCall

RealCall, 實現了Call接口,也是OkHttp里面唯一一個Call的實現類。

1. RealCall幾個重要的變量:
    final OkHttpClient client;
    final RetryAndFollowUpInterceptor retryAndFollowUpInterceptor;
    final Request originalRequest;

client :上節中已經對其進行介紹,RealCall 在構造方法中以參數的形式傳進來,供內部使用。

retryAndFollowUpInterceptor : 在第一節中也做過簡單介紹,是一個攔截器,處理重試,網絡錯誤,取消請求,以及請求重定向的一些操作。(后面會詳細學習分析)

**originalRequest : ** 原始的請求類。

2. RealCall里面有個幾個重要的方法:

execute() 同步請求

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

發起的一個同步的請求,如果重復調用會拋出異常。
captureCallStackTrace()是用來跟蹤調用棧的信息的。
后面就是把這個Call 加入到client的調度器里面,進行相應的線程管理。
最后就是調用getResponseWithInterceptorChain,這個在第一節做過分析,就是經過一堆攔截器,然后得到結果。

enqueue()異步請求

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

發起異步請求。如果重復調用會拋出異常。
captureCallStackTrace()同樣是用來跟蹤調用棧的信息的。
接下來,會新建一個AsyncCall,這個AsyncCall其實是一個Runnable線程,簡單過一下這個AsyncCall的代碼:

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

    //run的時候調用的方法
    @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);
      }
    }
  }

在execute的調用中,其實和同步調用時一樣的,只是這個是在異步線程中進行。

最后這個新建的AsyncCall ,同樣會通過client 添加到dispatcher當中,但是值得注意的是,同步和異步,其實是添加到dispatcher不同的List當中,進行管理的。

getResponseWithInterceptorChain()
調用一系列的攔截器,得到最終的結果,在第一節中對此做過解析,可以參考第一節最后的部分。這里就不做過多的說明,具體每個攔截器的作用,在后面會做學習分析。

cancel()
調用里面比較簡單,就是通過retryAndFollowUpInterceptor這個攔截器去對請求進行取消。對于正在執行的call 進行取消,但是對于已經是在讀寫數據階段的請求無法取消,而且會拋出異常。

  @Override public void cancel() {
    retryAndFollowUpInterceptor.cancel();
  }

總結

Request和RealCall, 在發起請求階段,是兩個重要的類。Request主要是接收了調用者的數據并進行加工處理;RealCall主要提供方法,進行同步或者異步的調用請求,還有就是取消請求的方法。

對于okhttp的整體以及前期的初始化的一些類也有所了解,接下來就是對每個攔截器進行解剖學習了。

系列:
OKhttp源碼學習(一)—— 基本請求流程
OKhttp源碼學習(二)—— OkHttpClient
OKhttp源碼學習(四)——RetryAndFollowUpInterceptor攔截器分析
OKhttp源碼學習(五)—— BridgeInterceptor
OKhttp源碼學習(六)—— CacheInterceptor攔截器
OKhttp源碼學習(七)—— ConnectInterceptor攔截器
OKhttp源碼學習(八)——CallServerInterceptor攔截器
OKhttp源碼學習(九)—— 任務管理(Dispatcher)

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

推薦閱讀更多精彩內容