OkHttp源码阅读(一)-——初识OkHttp

  OkHttp是由square公司研发一款开源的轻量级网络请求框架,一直备受Android端青睐,OkHttp的使用率远比Volley要高,同事square公司开发的Retrofit的使用也越来越多,Retrofit实际上对OKhttp有强制依赖性,其实质就是对OkHttp的封装,所以重点还是OkHttp,以下是个人的OKHttp深入学习,以此记录.

OKhttp的导入方式不再赘述,直接干活!

一个简单网络请求的执行流程

 /**
         * 同步请求
         */
        OkHttpClient client = new OkHttpClient.Builder().readTimeout(10000, TimeUnit.MILLISECONDS).build();
        Request request = new Request.Builder().url("www.sherlockaza.com").get().build();
        Call call = client.newCall(request);
        try {
            Response response = call.execute();
            String json = response.body().string();
            //解析
        } catch (IOException e) {
            e.printStackTrace();
        }
/**
         * 异步请求
         */
        OkHttpClient client = new OkHttpClient.Builder().readTimeout(10000, TimeUnit.MILLISECONDS).build();
        Request request = new Request.Builder().url("www.sherlockaza.com").get().build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().toString();
            }
        });

由上边两端代码可以看出,无论是同步请求还是异步请求,都需要几个重要的角色:

  1. OkHttpClient
  2. Request
  3. Call
    详细如下:

OkHttpClient

  OkHttpClient主要作用是封装了一个网络请求所需要的一些配置信息,通过下边源码可以看到,OkHttpClient拥有大量的成员变量,这些成员变量都是一个网络请求所需要携带的属性

final Dispatcher dispatcher;
  final @Nullable Proxy proxy;
  final List<Protocol> protocols;
  final List<ConnectionSpec> connectionSpecs;
  final List<Interceptor> interceptors;
  final List<Interceptor> networkInterceptors;
  final EventListener.Factory eventListenerFactory;
  final ProxySelector proxySelector;
  final CookieJar cookieJar;
  final @Nullable Cache cache;
  final @Nullable InternalCache internalCache;
  final SocketFactory socketFactory;
  final @Nullable SSLSocketFactory sslSocketFactory;
  final @Nullable CertificateChainCleaner certificateChainCleaner;
  final HostnameVerifier hostnameVerifier;
  final CertificatePinner certificatePinner;
  final Authenticator proxyAuthenticator;
  final Authenticator authenticator;
  final ConnectionPool connectionPool;
  final Dns dns;
  final boolean followSslRedirects;
  final boolean followRedirects;
  final boolean retryOnConnectionFailure;
  final int connectTimeout;
  final int readTimeout;
  final int writeTimeout;
  final int pingInterval;

譬如说请求超时时间,重试次数,连接池,分发器,拦截器等等,这里OkHttpClient使用了Builder构造者模式进行了OkHttpClient的初始化工作,

public Builder() {
      dispatcher = new Dispatcher();
      protocols = DEFAULT_PROTOCOLS;
      connectionSpecs = DEFAULT_CONNECTION_SPECS;
      eventListenerFactory = EventListener.factory(EventListener.NONE);
      proxySelector = ProxySelector.getDefault();
      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;
      connectTimeout = 10_000;
      readTimeout = 10_000;
      writeTimeout = 10_000;
      pingInterval = 0;
    }

什么是Builder构造者模式可以参考本人的这边博客设计模式之Builder模式,初始化的这些属性中比较重要的属性有Dispatcher 请求分发器,ConnectionPool连接池,Interceptor拦截器等等,这里先不赘述,后面一一介绍。

Request

   Request 顾名思义是一个网络请求,他的封装很简单

final HttpUrl url;
  final String method;
  final Headers headers;
  final @Nullable RequestBody body;
  final Object tag;

private volatile CacheControl cacheControl; // Lazily initialized.

请求URL、请求方法、请求头、还有Post请求需要的请求body,还有一个后面会用到取消请求的tag标记,不过有一个特殊成员变量是CacheControl,官方的注释是Lazily initialized.,并不是一开始就初始化,CacheControl的作用是缓存控制器,后边的网络缓存策略会使用到,先不赘述,同样Request的初始化方法也采用的是Builder模式.

Call

   Call是一个接口,他是链接RequestResponse之间的桥梁,Call的接口定义很简单

public interface Call extends Cloneable {
  /** Returns the original request that initiated this call. */
  Request request();

  /**
   * Invokes the request immediately, and blocks until the response can be processed or is in
   * error.
   *
   * <p>To avoid leaking resources callers should close the {@link Response} which in turn will
   * close the underlying {@link ResponseBody}.
   *
   * <pre>@{code
   *
   *   // ensure the response (and underlying response body) is closed
   *   try (Response response = client.newCall(request).execute()) {
   *     ...
   *   }
   *
   * }</pre>
   *
   * <p>The caller may read the response body with the response's {@link Response#body} method. To
   * avoid leaking resources callers must {@linkplain ResponseBody close the response body} or the
   * Response.
   *
   * <p>Note that transport-layer success (receiving a HTTP response code, headers and body) does
   * not necessarily indicate application-layer success: {@code response} may still indicate an
   * unhappy HTTP response code like 404 or 500.
   *
   * @throws IOException if the request could not be executed due to cancellation, a connectivity
   * problem or timeout. Because networks can fail during an exchange, it is possible that the
   * remote server accepted the request before the failure.
   * @throws IllegalStateException when the call has already been executed.
   */
  Response execute() throws IOException;

  /**
   * Schedules the request to be executed at some point in the future.
   *
   * <p>The {@link OkHttpClient#dispatcher dispatcher} defines when the request will run: usually
   * immediately unless there are several other requests currently being executed.
   *
   * <p>This client will later call back {@code responseCallback} with either an HTTP response or a
   * failure exception.
   *
   * @throws IllegalStateException when the call has already been executed.
   */
  void enqueue(Callback responseCallback);

  /** Cancels the request, if possible. Requests that are already complete cannot be canceled. */
  void cancel();

  /**
   * Returns true if this call has been either {@linkplain #execute() executed} or {@linkplain
   * #enqueue(Callback) enqueued}. It is an error to execute a call more than once.
   */
  boolean isExecuted();

  boolean isCanceled();

  /**
   * Create a new, identical call to this one which can be enqueued or executed even if this call
   * has already been.
   */
  Call clone();

  interface Factory {
    Call newCall(Request request);
  }
}
  1. execute()方法,同步网络请求调用的是execute方法
  2. enqueue方法,异步请求调用的方法
  3. cancel 取消请求方法
  4. 还有个内部接口返回一个Call对象

RealCall

  上边说到Call是一个接口,实际上的网络请求执行的方法都是交给他的子类RealCall

public class OkHttpClient implements Cloneable, Call.Factory, WebSocket.Factory {
        /**
         *
         * 
         *
         */
        @Override public Call newCall(Request request) {
            return RealCall.newRealCall(this, request, false /* for web socket */);
        }

    }

上边我们看出OkHttpClient实现了Call.Factory接口,并且该接口的实现内容是返回的Call的实现类RealCall。接下来调用excute或者enqueue方法进行网络请求

@Override public Response execute() throws IOException {
    //同步标记位,判断当前的请求是否已经执行过
    synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }

    captureCallStackTrace();//一些log信息
    eventListener.callStart(this);//网络时间监听的回调

    //--------------重要代码块start----------------//
    try {
      /**同步请求交给Dispatcher执行*/
      client.dispatcher().executed(this);
      /**最终得到的response要通过拦截器链一步一步的回调才能最终得到*/
      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);
    }
    //--------------重要代码块end----------------//
  }

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

同步和异步请求分别调用execute和enqueue方法,两个方法的实现截然不同,但都拥有一个重要的角色Dispatcher,无论是同步还是异步请求,实际上都是由Dispatcher调度分配的,源码中的注释比较粗略,下一篇会着重的分析Dispatcher调度原理。这篇内容主要是熟悉下一个网络请求的大致流程。

总结

根据以上的分析,简单的了解了一个Http请求的流程, 如图:

1.jpeg

接下来分析OKHttp的核心之一 Dispatcher

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容

  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    迷月闪星情阅读 10,534评论 0 11
  • 彩排完,天已黑
    刘凯书法阅读 4,167评论 1 3
  • 没事就多看看书,因为腹有诗书气自华,读书万卷始通神。没事就多出去旅游,别因为没钱而找借口,因为只要你省吃俭用,来...
    向阳之心阅读 4,765评论 3 11
  • 表情是什么,我认为表情就是表现出来的情绪。表情可以传达很多信息。高兴了当然就笑了,难过就哭了。两者是相互影响密不可...
    Persistenc_6aea阅读 123,111评论 2 7