OKHttp3原理分析

https://www.jianshu.com/p/310ccf5cbea6

写在前面

作为一名android开发者,要时时刻刻跟随技术的发展潮流,OKHttp作为当下最流行的网络请求框架我们不得不重视,它的原理也几乎是面试时必问的问题,故而对其进行学习并纪录之。

几个类

  • OKHttpClient
    okhttp3在项目中发起请求的代码如下:
    okHttpClient.newCall(request).execute();
    OKHttpClient 类中组合了很多的类对象,并且继承了Call.Factory,提供的方法只有一个:newCall,返回的是一个Call对象(实际是RealCall是Call的实现类)。
@Override 
public Call newCall(Request request) {
    return new RealCall(this, request);
  }

使用okHttpClient最好创建一个单例,因为每一个client都有自己的一个连接池connection pool和线程池thread pools。重用这些连接池和线程池可以减少延迟和节约内存。
okHttpClient使用了builder模式

public static final class Builder {
    Dispatcher dispatcher;
    Proxy proxy;
    List<Protocol> protocols;
    List<ConnectionSpec> connectionSpecs;
    final List<Interceptor> interceptors = new ArrayList<>();
    final List<Interceptor> networkInterceptors = new ArrayList<>();
    ProxySelector proxySelector;
    CookieJar cookieJar;
    Cache cache;
    InternalCache internalCache;
    SocketFactory socketFactory;
    SSLSocketFactory sslSocketFactory;
    CertificateChainCleaner certificateChainCleaner;
    HostnameVerifier hostnameVerifier;
    CertificatePinner certificatePinner;
    Authenticator proxyAuthenticator;
    Authenticator authenticator;
    ConnectionPool connectionPool;
    Dns dns;
    boolean followSslRedirects;
    boolean followRedirects;
    boolean retryOnConnectionFailure;
    int connectTimeout;
    int readTimeout;
    int writeTimeout;
    ...
}

可以看到OKHttpClient中包含的所有字段。

  • Dispatcher
    Dispatcher我们可以理解为一个执行策略(官方这样说的:Policy on when async requests are executed.),当我们调用newCall时,它不断的从RequestQueue中取出请求(Call),该引擎有同步和异步请求,同步请求通过Call.execute()直接返 回当前的Response,而异步请求会把当前的请求Call.enqueue添加(AsyncCall)到请求队列中,并通过回调(Callback) 的方式来获取最后结果。
synchronized void executed(RealCall call) {
    runningSyncCalls.add(call);
  }

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

注意到,这里enqueue方法中有一个判断:如果当前运行的异步请求队列长度小于最大请求数,也就是64,并且主机的请求数小于每个主机的请求数也就是5,则把当前请求添加到 运行队列,接着交给线程池ExecutorService处理,否则则放置到readAsyncCall进行缓存,等待执行。

  • Call
public interface Call {

  Request request();

  Response execute() throws IOException;

  void enqueue(Callback responseCallback);

  void cancel();

  boolean isExecuted();

  boolean isCanceled();

  interface Factory {
    Call newCall(Request request);
  }
}

Call是一个接口类,定义了Http请求的方法,并提供了一个内部接口Factory,OkHttpClient即实现了该接口。

  • RealCall
    RealCall是Call的实现类,里面最主要的两个方法是execute和enqueue。
final class RealCall implements Call {
   ...
   @Override
    public Response execute() throws IOException {
       synchronized (this) {
         if (executed) throw new IllegalStateException("Already Executed");
         executed = true;
       }
       try {
         client.dispatcher().executed(this);
         Response result = getResponseWithInterceptorChain();
         if (result == null) throw new IOException("Canceled");
         return result;
       } finally {
         client.dispatcher().finished(this);
       }
     }
   ...
   @Override 
   public void enqueue(Callback responseCallback) {
       synchronized (this) {
         if (executed) throw new IllegalStateException("Already Executed");
         executed = true;
       }
       client.dispatcher().enqueue(new AsyncCall(responseCallback));
     }
   ...
}

可以看到该类中的execute和enqueue都调用了dispatcher中的executed和enqueue(代码前面已贴)。
上面的代码中也可以解释我们前面所说的:“同步请求通过Call.execute()直接返 回当前的Response,而异步请求会把当前的请求Call.enqueue添加(AsyncCall)到请求队列中,并通过回调(Callback) 的方式来获取最后结果。”
execute通过getResponseWithInterceptorChain获取返回Response。
同步方法上面的代码已经足够了, 这里重点说一下异步请求如何获得返回的结果:
再回到Dispatcher类,enqueue异步方法中执行了executorService().execute(call),executorService()代码如下:

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

可以看到上面的代码中用到了线程池,这也就意味着后半句的executor(call)必然涉及到了多线程的问题,我们来看代码:

public interface Executor {
    void execute(Runnable command);
}

可以看到execute的参数是一个Runnable,这也意味着AsyncCall必然是一个Runnable的子类。下面来看AsyncCall的源码:

  • AsyncCall
final class AsyncCall extends NamedRunnable {
    private final Callback responseCallback;

    private AsyncCall(Callback responseCallback) {
      super("OkHttp %s", redactedUrl().toString());
      this.responseCallback = responseCallback;
    }
   ...
    @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 {
          responseCallback.onFailure(RealCall.this, e);
        }
      } finally {
        client.dispatcher().finished(this);
      }
    }
  }
   ...
}

从上面的代码中我们可以看到AysncCall继承自NamedRunnable抽象类,并且会执行execute方法,而execute方法中我们又看到了熟悉的代码:
Response response = getResponseWithInterceptorChain();
可见返回结果也是通过调用这个方法得到的,只不过与同步相比中间增加了一些过程,并且请求结果是通过responseCallBack返回。
我们来看一下这个方法的代码:

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

可以看到,这个方法中主要是用到了Interceptor类。

  • Interceptor
public interface Interceptor {
  Response intercept(Chain chain) throws IOException;

  interface Chain {
    Request request();

    Response proceed(Request request) throws IOException;

    Connection connection();
  }
}

Interceptor接口代码很少,但是;却是okhttp中非常核心的类,它把实际的网络请求、缓存、透明压缩等功能都统一了起来,每一个功能都是一个Interceptor,它们再连成一个Interceptor.Chain,环环相扣,完成一次网络请求。
分析getResponseWithInterceptorChain()方法中用到的interceptor:
1,通过client设置的interceptors(即builder.addInterceptor())
2,RetryAndFollowUpInterceptor,负责重试和重定向
3,BridgeInterceptor,首先将应用层的数据类型转换为网络调用层的数据类型,然后将网络层返回的数据类型转换为应用层的数据类型
4,CacheInterceptor,负责读取缓存,更新缓存
5,ConnectInterceptor,负责和服务器建立起链接
6,networkInterceptors,client设置的networkInterceptor
7,CallServerInterceptor,负责向服务器发送请求数据、从服务器读取响应数据
最后一个interceptor是负责跟服务器通讯的,其他的interceptor配置都要在此之前。

@Override public Response intercept(Chain chain) throws IOException {
    HttpStream httpStream = ((RealInterceptorChain) chain).httpStream();
    StreamAllocation streamAllocation = ((RealInterceptorChain) chain).streamAllocation();
    Request request = chain.request();

    long sentRequestMillis = System.currentTimeMillis();
    httpStream.writeRequestHeaders(request);

    if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
      Sink requestBodyOut = httpStream.createRequestBody(request, request.body().contentLength());
      BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
      request.body().writeTo(bufferedRequestBody);
      bufferedRequestBody.close();
    }

    httpStream.finishRequest();

    Response response = httpStream.readResponseHeaders()
        .request(request)
        .handshake(streamAllocation.connection().handshake())
        .sentRequestAtMillis(sentRequestMillis)
        .receivedResponseAtMillis(System.currentTimeMillis())
        .build();

    if (!forWebSocket || response.code() != 101) {
      response = response.newBuilder()
          .body(httpStream.openResponseBody(response))
          .build();
    }
    ...
    return response;
  }

Http请求流程图


 

猜你喜欢

转载自blog.csdn.net/asdasdasd123123123/article/details/86495009