美文网首页Android基础知识
【Android】okhttp3流程源码

【Android】okhttp3流程源码

作者: 秀叶寒冬 | 来源:发表于2019-06-26 23:02 被阅读9次

    1 okhttp3总体流程

    下图摘抄自网络


    图1.1 okHttp3总体流程图

     

    2 Request、Response、Call基本概念

    • Request
      request主要是对url,请求方法,请求参数,请求头等参数进行初始化,是通过Builder模式进行初始化
    • Response
      请求返回给用户的一些参数,如协议,响应码,信息,返回数据等。
    • Call
      Call是一个接口,它的实现类是RealCall。RealCall是final类型,是不可被继承的。RealCall主要作用是发送请求、建立拦截器和异步回调。请求方式有同步请求execute和异步请求enqueue。

    2.1 OkHttp3总体流程解析

    • 初始化OkHttpClient对象,可以直接new一个对象,也可以通过Builder方法来build一个对象
    • 初始化一个Request对象,Request类主要是对url、请求参数、请求头以及请求方法进行初始化
    • 通过okHttpClient.newCall来初始化一个Call对象,newCall方法有个Request参数,该参数是上一步初始化的Request对象
    • 然后通过初始化的call对象调用异步请求方法enqueue()或者同步请求方法execute(),如果call调用的是异步请求方法enqueue(),则会调用Dispatcher类的enqueue(AsyncCall)方法,最终会执行AsyncCall的execute()方法。
    • 同步方法enquene()和异步方法execute()最终都会调用getResponseWithInspectorChain()方法,该方法会初始化几个拦截器,利用拦截器分层实现缓存、透明压缩、网络 IO 等功能。
    • 最后通过Response返回请求的结果信息。

    2.2 流程源码

    • 初始化OkHttpClient对象,可以直接new一个对象,也可以通过Builder方法来build一个对象
      private OkHttpClient(Builder builder) {
        this.dispatcher = builder.dispatcher;
        this.proxy = builder.proxy;
        this.protocols = builder.protocols;
        this.connectionSpecs = builder.connectionSpecs;
        this.interceptors = Util.immutableList(builder.interceptors);
        this.networkInterceptors = Util.immutableList(builder.networkInterceptors);
        this.proxySelector = builder.proxySelector;
        this.cookieJar = builder.cookieJar;
        this.cache = builder.cache;
        this.internalCache = builder.internalCache;
        this.socketFactory = builder.socketFactory;
    
        boolean isTLS = false;
        for (ConnectionSpec spec : connectionSpecs) {
          isTLS = isTLS || spec.isTls();
        }
    
        if (builder.sslSocketFactory != null || !isTLS) {
          this.sslSocketFactory = builder.sslSocketFactory;
          this.certificateChainCleaner = builder.certificateChainCleaner;
        } else {
          X509TrustManager trustManager = systemDefaultTrustManager();
          this.sslSocketFactory = systemDefaultSslSocketFactory(trustManager);
          this.certificateChainCleaner = CertificateChainCleaner.get(trustManager);
        }
    
        this.hostnameVerifier = builder.hostnameVerifier;
        this.certificatePinner = builder.certificatePinner.withCertificateChainCleaner(
            certificateChainCleaner);
        this.proxyAuthenticator = builder.proxyAuthenticator;
        this.authenticator = builder.authenticator;
        this.connectionPool = builder.connectionPool;
        this.dns = builder.dns;
        this.followSslRedirects = builder.followSslRedirects;
        this.followRedirects = builder.followRedirects;
        this.retryOnConnectionFailure = builder.retryOnConnectionFailure;
        this.connectTimeout = builder.connectTimeout;
        this.readTimeout = builder.readTimeout;
        this.writeTimeout = builder.writeTimeout;
      }
    
        public OkHttpClient build() {
          return new OkHttpClient(this);
        }
    
    • 初始化一个Request对象,Request类主要是对url、请求参数、请求头以及请求方法进行初始化
        public Request build() {
          if (url == null) throw new IllegalStateException("url == null");
          return new Request(this);
        }
    
    • 通过okHttpClient.newCall来初始化一个Call对象,newCall方法有个Request参数,该参数是上一步初始化的Request对象。执行newCall时会初始化一个RealCall对象,该对象实现了call接口。
      @Override public Call newCall(Request request) {
        return new RealCall(this, request);
      }
    
    • 然后通过初始化的call对象调用异步请求方法enqueue()或者同步请求方法execute()。
      (1)如果call调用的是异步请求方法enqueue(),则会调用Dispatcher类的enqueue(AsyncCall)方法,最终会执行AsyncCall的execute()方法。
    //RealCall的enqueue方法
      void enqueue(Callback responseCallback, boolean forWebSocket) {
        synchronized (this) {
          if (executed) throw new IllegalStateException("Already Executed");
          executed = true;
        }
        client.dispatcher().enqueue(new AsyncCall(responseCallback, forWebSocket));
      }
    
    //Dispatcher方法的enqueue方法
      synchronized void enqueue(AsyncCall call) {
        if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
          runningAsyncCalls.add(call);
          //executorService()返回的是ExecutorService对象,该对象用的是线程池ThreadPoolExecutor进行初始化
          executorService().execute(call);
        } else {
          readyAsyncCalls.add(call);
        }
      }
    
    //AsyncCall的execute方法
        @Override protected void execute() {
          boolean signalledCallback = false;
          try {
            Response response = getResponseWithInterceptorChain(forWebSocket);
            if (canceled) {
              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);
          }
        }
      }
    

    (2)使用call调用同步方法execute

    @Override protected void execute() {
          boolean signalledCallback = false;
          try {
            Response response = getResponseWithInterceptorChain(forWebSocket);
            if (canceled) {
              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);
          }
        }
    

    由上可得,不管同步还是异步,最终都会调用getResponseWithInterceptorChain(forWebSocket);方法。该方法会初始化几个拦截器,利用拦截器分层实现缓存、透明压缩、网络 IO 等功能。

    private 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 (!retryAndFollowUpInterceptor.isForWebSocket()) {
        interceptors.addAll(client.networkInterceptors());
      }
      interceptors.add(new CallServerInterceptor(
          retryAndFollowUpInterceptor.isForWebSocket()));
    
      Interceptor.Chain chain = new RealInterceptorChain(
          interceptors, null, null, null, 0, originalRequest);
      return chain.proceed(originalRequest);
    }
    
    • 在配置 OkHttpClient 时设置的 interceptors;
    • 负责失败重试以及重定向的 RetryAndFollowUpInterceptor;
    • 负责把用户构造的请求转换为发送到服务器的请求、把服务器返回的响应转
    • 为用户友好的响应的 BridgeInterceptor;
    • 负责读取缓存直接返回、更新缓存的 CacheInterceptor;
    • 负责和服务器建立连接的 ConnectInterceptor;
    • 配置 OkHttpClient 时设置的 networkInterceptors;
    • 负责向服务器发送请求数据、从服务器读取响应数据的CallServerInterceptor。
    • 最后通过Response返回请求的结果信息。
      Request(Builder builder) {
        this.url = builder.url;
        this.method = builder.method;
        this.headers = builder.headers.build();
        this.body = builder.body;
        this.tags = Util.immutableMap(builder.tags);
      }
    

    相关文章

      网友评论

        本文标题:【Android】okhttp3流程源码

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