美文网首页
OkHttp源码阅读(一)-——初识OkHttp

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

作者: Sherlock丶Aza | 来源:发表于2021-04-10 08:05 被阅读0次

      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

    相关文章

      网友评论

          本文标题:OkHttp源码阅读(一)-——初识OkHttp

          本文链接:https://www.haomeiwen.com/subject/agoykltx.html