美文网首页
OkHttp3 学习笔记

OkHttp3 学习笔记

作者: feifei_fly | 来源:发表于2019-08-29 16:07 被阅读0次
    image.png

    OkHttp的基本使用

    String url = "http://wwww.baidu.com";
    //(1)创建一个OKhttpClient
    OkHttpClient okHttpClient = new OkHttpClient();
    
    //(2)创建一个Request
    final Request request = new Request.Builder()
            .url(url)
            .build();
    //(3)okHttpClient 调用newCall()方法 创建一个Call对象
    Call call = okHttpClient.newCall(request);
    //(4)call调用enqueue()方法,这次请求Call添加到任务队列,并通过CallBack接收返回结果。
    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());
        }
    });
    
    • 在OkHttp3中,每一个请求任务都封装为一个Call,其实现为RealCall。
    • 而所有的策略几乎都可以通过OkHttpClient传入
    • 所有全局策略与数据,除了存储在允许上层访问的OkHttpClient实例以外,还有一部分是存储在只允许包可见的Internal.instance中(如连接池、路由黑名单等)
    • OkHttp中用户可传入的interceptor分为两类,一类是全局interceptor,该类interceptor在请求开始之前最早被调用,另外一类为非网页请求的networkInterceptor,这类interceptor只有在非网页请求中会被调用,并且是在组装完成请求之后,真正发起请求之前被调用(这块具体可以参看RealCall#getResponseWithInterceptorChain()方法)
    • 整个请求过程通过RealInterceptorChain#proceed来连接,在每个interceptor中调用下一个interceptor来完成整个请求流程,并且在回到当前interceptor后完成响应处理
    • 在异步请求中,我们通过Callback来获得简单清晰的请求回调(onFailure、onResponse)
    • 在OkHttpClient中,我们可以传入EventListener的工厂方法,为每一个请求创建一个EventListener,来接收非常细的事件回调

    realCall.enqueue() 的具体调用过程,如下图

    image

    一、OKHttp3 原理介绍

    1、okHttp中大量使用了Builder设置模式

    OkHttpClient.Builder
    Request.Builder
    

    Builder机制的优势是 可以规避大量参数构造方法不灵活的缺点,和set方法不能保证对象的合法性问题。并且Builder采用链式调用,使用方便灵活。

    2、Request 类

    Request类其实是一个数据承载类,主要承载网络请求的参数信息,代表着一个网络请求。如method(get 或post),HttpUrl(scheme、host、port),headers 和RequestBody

    public final class Request {
      final HttpUrl url;
      final String method;
      final Headers headers;
      final @Nullable RequestBody body;
      final Object tag;
    
      private volatile CacheControl cacheControl; // Lazily initialized.
    
      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;
      }
    }
    

    3、OkHttpClient 类,也是一个载体类,一个工具箱。它承载http请求相关的策略参数、拦截器、调度分发器、超时时间、连接池等。

    public class OkHttpClient implements Cloneable, Call.Factory, WebSocket.Factory {
     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 继承自Call.Factory,实现了newCall()方法

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

    RealCall类中newRealCall()

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

    okHttpClient的newCall方法内部调用的是RealCall的newRealCall()方法,传入okHttpClient对象(一个公共工具箱)和Request对象(什么网络请求),返回一个RealCalL对象。

    4、RealCall 类

    RealCall集成自Call接口

    public interface Call extends Cloneable {
    
      //返回request请求
      Request request();
    
      //同步执行网络请求
      Response execute() throws IOException;
    
      //异步执行网路请求
      void enqueue(Callback responseCallback);
    
     //取消执行
      void cancel();
    
      boolean isExecuted();
    
      boolean isCanceled();
    
      Call clone();
    
      interface Factory {
        Call newCall(Request request);
      }
    
    

    RealCall类是网络请求的具体实施类。持有OkhttpClient(大工具箱),和Request对象(网络请求)

    (1)execute() 同步执行网路请求
      @Override public Response execute() throws IOException {
        synchronized (this) {
        
          //保证仅执行一次
          if (executed) throw new IllegalStateException("Already Executed");
          executed = true;
        }
        captureCallStackTrace();
        eventListener.callStart(this);
        try {
          //将该Call 添加到分发器中的同步队列中.
          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 {
          // realCall执行完成,尝试将待执异步任务添加到 异步执行队列
          client.dispatcher().finished(this);
        }
      }
    
    (2)enqueue() 异步执行网络请求
     @Override public void enqueue(Callback responseCallback) {
        synchronized (this) {
          if (executed) throw new IllegalStateException("Already Executed");
          executed = true;
        }
        captureCallStackTrace();
        eventListener.callStart(this);
        //将RealCall 封装成一个AsyncCall同时添加到异步执行队列中。
        client.dispatcher().enqueue(new AsyncCall(responseCallback));
      }
    

    AsyncCall 继承自NamedRunnable类,同时是RealCall的内部类,真正的执行过程位于execute中。

    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;
        }
    
        @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);
          }
        }
      }
    
    
    (3)网络请求真正被执行的地方

    getResponseWithInterceptorChain() 方法
    可以看到该方法中天剑了一个Interceptor.Chain 拦截器链,同时添加了很多连接器。

    真正的网络请求在CallServerInterceptor 拦截器中处理

    
      Response getResponseWithInterceptorChain() throws IOException {
        // Build a full stack of interceptors.
        List<Interceptor> interceptors = new ArrayList<>();
        interceptors.addAll(client.interceptors());
        interceptors.add(retryAndFollowUpInterceptor);
        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);
      }
    }
    
    5、 Dispatcher类 负责任务的分发
    • Dispatcher 内部持有一个线程池
    • 持有两个异步队列readyAsyncCalls(待执行异步任务队列)和runningAsyncCalls(正在执行的异步任务队列)
    • 持有一个同步队列:runningSyncCalls(正在执行的同步任务)
    public final class Dispatcher {
      private int maxRequests = 64;
      private int maxRequestsPerHost = 5;
      private @Nullable Runnable idleCallback;
    
      /** Executes calls. Created lazily. */
      private @Nullable ExecutorService executorService;
    
      /** 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<>();
    
      public Dispatcher(ExecutorService executorService) {
        this.executorService = executorService;
      }
    
      public Dispatcher() {
      }
    
      public synchronized ExecutorService executorService() {
        if (executorService == null) {
          executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
              new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false));
        }
        return executorService;
      }
    }
    
    队列管理

    异步任务入列时,首先会判断 正在执行的异步任务个数是否小于可同时执行的任务个数,若是,则将call添加到runningAsyncCalls队列,同时在线程池中执行该Call任务

    若否,说明任务忙,将Call添加到等待执行队列readyAsyncCalls

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

    当某个任务执行完成后,都会调用promoteCalls(),尝试将等待队列中的任务,切换到正在执行队列,并在线程池中执行call任务。

    
      private void promoteCalls() {
        if (runningAsyncCalls.size() >= maxRequests) return; // Already running max capacity.
        if (readyAsyncCalls.isEmpty()) return; // No ready calls to promote.
    
        for (Iterator<AsyncCall> i = readyAsyncCalls.iterator(); i.hasNext(); ) {
          AsyncCall call = i.next();
    
          if (runningCallsForHost(call) < maxRequestsPerHost) {
            i.remove();
            runningAsyncCalls.add(call);
            executorService().execute(call);
          }
    
          if (runningAsyncCalls.size() >= maxRequests) return; // Reached max capacity.
        }
      }
    
    /** Used by {@code Call#execute} to signal completion. */
      void finished(RealCall call) {
        finished(runningSyncCalls, call, false);
      }
    
      private <T> void finished(Deque<T> calls, T call, boolean promoteCalls) {
        int runningCallsCount;
        Runnable idleCallback;
        synchronized (this) {
          if (!calls.remove(call)) throw new AssertionError("Call wasn't in-flight!");
          if (promoteCalls) promoteCalls();
          runningCallsCount = runningCallsCount();
          idleCallback = this.idleCallback;
        }
    
        if (runningCallsCount == 0 && idleCallback != null) {
          idleCallback.run();
        }
      }
    

    二、OKHttp 中拦截器链是其整个框架的精髓

    用户可传入的 interceptor 分为两类:

    • ①一类是全局的 interceptor,该类 interceptor 在整个拦截器链中最早被调用,通过 OkHttpClient.Builder#addInterceptor(Interceptor) 传入;
    • ②另外一类是非网页请求的 interceptor ,这类拦截器只会在非网页请求中被调用,并且是在组装完请求之后,真正发起网络请求前被调用,所有的 interceptor 被保存在 List<Interceptor> interceptors 集合中,按照添加顺序来逐个调用。具体可参考 RealCall#getResponseWithInterceptorChain() 方法。通过 OkHttpClient.Builder#addNetworkInterceptor(Interceptor) 传入;
    image

    三、如何实现一个拦截器

    1、定义拦截器接口Interceptor 和连接器链Chain

    • Interceptor 最主要方法是intercept(),参数为拦截链,返回值为Respone结果。
    • Interceptor.Chain 拦截器链最主要的方法为proceed()参数为Request
    public interface Interceptor {
      Response intercept(Chain chain) throws IOException;
    
      interface Chain {
        Request request();
    
        Response proceed(Request request) throws IOException;
    
        @Nullable Connection connection();
    
        Call call();
      }
    }
    

    2、实现Interceptor 定义具体的拦截器

    实现intercept()方法

    • 请求预处理过程:取出原始request ,对原始request请求做相应的处理,生产一个新的Request
    • 调用chain.proceed,将新request传递到下一个拦截器进行处理
    • 下一个拦截器返回处理结果后,可以对结果进行二次处理,返回给上一个拦截器。
    public final class BridgeInterceptor implements Interceptor {
      private final CookieJar cookieJar;
    
      public BridgeInterceptor(CookieJar cookieJar) {
        this.cookieJar = cookieJar;
      }
    
      @Override public Response intercept(Chain chain) throws IOException {
      
        //(1)取出原始request ,对原始request请求做相应的处理,生产一个新的Request
        Request userRequest = chain.request();
        Request.Builder requestBuilder = userRequest.newBuilder();
    
    
        if (userRequest.header("Host") == null) {
          requestBuilder.header("Host", hostHeader(userRequest.url(), false));
        }
    
        //(2)将新request传递到下一个拦截器进行处理
        Response networkResponse = chain.proceed(requestBuilder.build());
    
    
        //(3)获取到下一个拦截器处理的结果,可以对结果进行一些后处理。然后返回给上一个拦截器。
        HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
    
        Response.Builder responseBuilder = networkResponse.newBuilder()
            .request(userRequest);
    
        if (transparentGzip
            && "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
            && HttpHeaders.hasBody(networkResponse)) {
          GzipSource responseBody = new GzipSource(networkResponse.body().source());
          Headers strippedHeaders = networkResponse.headers().newBuilder()
              .removeAll("Content-Encoding")
              .removeAll("Content-Length")
              .build();
          responseBuilder.headers(strippedHeaders);
          String contentType = networkResponse.header("Content-Type");
          responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
        }
    
        return responseBuilder.build();
      }
    

    3、实现具体的Interceptor.Chain

    public final class RealInterceptorChain implements Interceptor.Chain{
        
        //interceptors 数组
        private final List<Interceptor> interceptors;
        //index指示当前 需要哪个Interceptor 处理Request
        private final int index;
        //记录当前的request请求
        private final Request request;
            
            
     @Override public Response proceed(Request request) throws IOException {
        return proceed(request, streamAllocation, httpCodec, connection);
      }
    
    
      public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
          RealConnection connection) throws IOException {
        if (index >= interceptors.size()) throw new AssertionError();
    
     
    
        //(1)Clone出一个新的RealInterceptorChain,更新原来的requst,index+1,将当前interceptor的下一个拦截器为当前的interceptor。
        RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
            connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
            writeTimeout);
        
        //(2)执行当前interceptor的intercept()方法,将Clone出来的  RealInterceptorChain 作为参数传递给拦截器。
        Interceptor interceptor = interceptors.get(index);
        Response response = interceptor.intercept(next);
    
    
        //返回response
        return response;
      }
    }
    

    到此 一个建议的拦截器链 完成。拦截器有很多应用,如Okhttp库,组件化方法CC库都用拦截器实现了其核心接口。

    四、参考文章

    https://www.jianshu.com/p/9deec36f2759

    相关文章

      网友评论

          本文标题:OkHttp3 学习笔记

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