1. 程式人生 > >OKhttp原始碼解析---Request建立

OKhttp原始碼解析---Request建立

建立請求主要是一下幾步

        requestBuilder.method("GET", null);
        Request request = requestBuilder.build();
        Call mcall = mOkHttpClient.newCall(request);

先看
new Request.Builder().url("http://www.baidu.com");

先呼叫Request的Builder方法
    public Builder() {
      this.method = "GET";
      this.headers = new Headers.Builder();
    }
method預設設定為GET,建立一哥 Headers.Builder

然後是url方法

public Builder url(String url) {
      if (url == null) throw new NullPointerException("url == null");

      // Silently replace websocket URLs with HTTP URLs.
      if (url.regionMatches(true, 0, "ws:", 0, 3)) {
        url = "http:" + url.substring(3);
      } else if (url.regionMatches(true, 0, "wss:", 0, 4)) {
        url = "https:" + url.substring(4);
      }

      HttpUrl parsed = HttpUrl.parse(url);
      if (parsed == null) throw new IllegalArgumentException("unexpected url: " + url);
      return url(parsed);
    }
    public Builder url(HttpUrl url) {
      if (url == null) throw new NullPointerException("url == null");
      this.url = url;
      return this;
    }
解析url並儲存到url變數

method方法設定請求方法型別和body

 public Builder method(String method, RequestBody body) {
      if (method == null) throw new NullPointerException("method == null");
      if (method.length() == 0) throw new IllegalArgumentException("method.length() == 0");
      if (body != null && !HttpMethod.permitsRequestBody(method)) {
        throw new IllegalArgumentException("method " + method + " must not have a request body.");
      }
      if (body == null && HttpMethod.requiresRequestBody(method)) {
        throw new IllegalArgumentException("method " + method + " must have a request body.");
      }
      this.method = method;
      this.body = body;
      return this;
    }

接下來是
Request request = requestBuilder.build();

    public Request build() {
      if (url == null) throw new IllegalStateException("url == null");
      return new Request(this);
    }

  private 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;
  }
最後一個是建立Call
Call mcall = mOkHttpClient.newCall(request);
  @Override public Call newCall(Request request) {
    return new RealCall(this, request);
  }
這裡返回的RealCall

  protected RealCall(OkHttpClient client, Request originalRequest) {
    this.client = client;
    this.originalRequest = originalRequest;
    this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client);
  }
這裡主要建立了一個RetryAndFollowUpInterceptor
RetryAndFollowUpInterceptor是一個失敗重試和重定向的攔截器。

這樣request請求就建立了。