OkHttp源码分析
来源:互联网 发布:闪电网络测速工具 编辑:程序博客网 时间:2024/06/08 12:10
前言
当架构一个新的App,最先想到的框架应该要属图片框架和网络框架了,所以我打算花一些时间来研究这两方面框架的源码,图片加载框架我选的是Glide,如果有感兴趣的朋友可以去看看我之前写的Glide的源码分析http://blog.csdn.net/luofen521/article/details/71213440;网络框架我选的是Okhttp。
正文
这篇文章主要分析OkHttp3.8.1的源码,下面是OkHttp进行一次最基本的Get请求流程:
/** * Get请求 */ private void useGet() { //1.创建OKHttpClient对象 OkHttpClient mOkHttpClient = new OkHttpClient(); //2.创建一个Request对象 Request request = new Request.Builder().url("http://www.baidu.com/").build(); //3.new Call Call call = mOkHttpClient.newCall(request); //4.请求加入调度 call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_LONG).show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { //注意,这个方法是在子线程中回调的所以不能直接更新UI final String result = response.body().string(); MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "请求成功,结果:" + result, Toast.LENGTH_LONG).show(); } }); } }); }
由上面的代码可知,一次OkHttp的完整请求,主要分为以下4个步骤:
- 创建一个OkHttpClient对象
- 构建一个Request对象,其中包含了url等信息
- 通过OkHttpClient和Request对象,构建出Call对象
- 把Call对象加入到调度中,并注入了一个Callback对象,以便对网络请求结果分发处理
这样就完成了一次完整的网络请求,网络请求完成以后,会回调Callback的响应方法,如果失败,则回调onFailure方法;如果成功,则回调onResponse方法,请求到的结果在其Response对象中,注意的一点就是,这两个方法都是在子线程中回调的。所以,如果要更新UI等操作,需要切换到主线程。
那我们来看看上述的四步,具体执行了哪些操作。
1.创建OkHttpClient
也就是下面这句代码:
OkHttpClient mOkHttpClient = new OkHttpClient();
我们到OkHttpClient中看看它的构造方法,如下:
public OkHttpClient() { this(new Builder()); }
可以看到,这里主要是创建了一个Builder对象,然后调用了OkHttpCilent重载的构造方法,我们先看看Builder的构造方法:
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创建对象的模式,也就是用Builder对象来封装OkHttpClient初始化所需要的参数,然后传递Builder对象到OkHttpClient构造方法里,完成OkHttpClient对象属性的初始化。当创建一个对象需要很多参数时,这是一个比较好的方式,在OkHttp中,随处可见这种方式,接下来看看OkHttpClient的有参构造方法:
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.eventListenerFactory = builder.eventListenerFactory; 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; this.pingInterval = builder.pingInterval; }
可以看到OkHttpClient的构造方法,就是初始化一些参数,这些参数包括证书验证、网络请求超时时间等。
2.创建Request对象
Request request = new Request.Builder().url("http://www.baidu.com/").build();
可以看出Request的创建方式也是Builder模式,然后通过链式调用可以给Request指定url、header等。接下里,我们看看具体构建细节。先看看Request中内部类Builder的构造方法:
public Builder() { this.method = "GET"; this.headers = new Headers.Builder(); }
这里首先指定了请求方式为”GET”的方式,然后创建了一个Headers的内部类Builder对象,用于保存header信息。
接下来,看看Request中内部类Builder的url方法,如下:
public Builder url(String url) { if (url == null) throw new NullPointerException("url == null"); // Silently replace web socket URLs with HTTP URLs. if (url.regionMatches(true, 0, "ws:", 0, 3)) { url = "http:" + url.substring(3); } else if (url.regionMatches(true, 0, "wss:", 0, 4)) { url = "https:" + url.substring(4); } HttpUrl parsed = HttpUrl.parse(url); if (parsed == null) throw new IllegalArgumentException("unexpected url: " + url); return url(parsed); } public Builder url(HttpUrl url) { if (url == null) throw new NullPointerException("url == null"); this.url = url; return this; }
这里,我们只关心主流程,在最后一行,调用了url(HttpUrl url)的重载方法,在这个方法里,为Builder指定了url,并把当前Builder对象返回。
最后看一下build方法
public Request build() { if (url == null) throw new IllegalStateException("url == null"); return new Request(this); }
这里直接创建了一个Request对象,并把当前Builder的对象传递过去,很明显,就是把之前配置的请求方式、url、header等赋值给Request对象,看看Request的构造方法:
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; }
可以看到,创建Request就是为其指定了请求方式、url、header等信息。
3.构建Call对象
在第1步创建出了OkHttpClient,在第2步,构建了携带请求信息的Request对象。第3步就是通过前两步得到的OkHttpClient对象和Request对象,构建出Call对象。如下:
Call call = mOkHttpClient.newCall(request);
我们到OkHttpClient中看看newCall方法,如下:
@Override public Call newCall(Request request) { return new RealCall(this, request, false /* for web socket */); }
Call是一个接口,这里直接创建了它的实现类RealCall对象,并返回。接下来,看看RealCall的构造方法:
RealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) { final EventListener.Factory eventListenerFactory = client.eventListenerFactory(); this.client = client; this.originalRequest = originalRequest; this.forWebSocket = forWebSocket; this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client, forWebSocket); // TODO(jwilson): this is unsafe publication and not threadsafe. this.eventListener = eventListenerFactory.create(this); }
可以看到,RealCall中持有了在前两步初始化的OkHttpClient对象和Request对象。
4.把Call加入调度
前三步都没有看到发起真正的网络请求,没错,网络请求的真正实现就是在第4步中完成的。先看Call怎么加入调度中的:
call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_LONG).show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { //注意,这个方法是在子线程中回调的所以不能直接更新UI final String result = response.body().string(); MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "请求成功,结果:" + result, Toast.LENGTH_LONG).show(); } }); } });
enqueue方法会传递一个Callback对象进去,用于请求结束以后,接口回调。由于第3步得到的是一个RealCall对象,我们先来看看RealCall中的enqueue方法:
@Override public void enqueue(Callback responseCallback) { synchronized (this) { if (executed) throw new IllegalStateException("Already Executed"); executed = true; } captureCallStackTrace(); client.dispatcher().enqueue(new AsyncCall(responseCallback)); }
可以看到,这个方法首先用synchronized关键字,锁住了当前对象,也就是RealCall对象,然后对executed字段进行判断,那executed是什么呢?它是用于表示Call实例有没有执行过,当为true时,表示已经执行过了,这里就会抛出”Alread Executed”的错误信息,可见,第三步得到的Call对象,只能被执行一次。
然后看最后一行,先是通过传递进来的Callback对象封装成了一个AsyncCall对象,那AsyncCall又是个什么类呢?它其实是RealCall中的内部类,我们来看看它的定义:
final class AsyncCall extends NamedRunnable {
AsyncCall继承于NamedRunnable,那NamedRunnable是继承Runnable么?我们来看看它的定义:
public abstract class NamedRunnable implements Runnable {
果然如此,那我们看看AsyncCall的构造方法:
AsyncCall(Callback responseCallback) { super("OkHttp %s", redactedUrl()); this.responseCallback = responseCallback; }
可知,这里只是把回调对象赋值给了AsyncCall中的属性,我们继续回到RealCall类中的enqueue方法:
@Override public void enqueue(Callback responseCallback) { synchronized (this) { if (executed) throw new IllegalStateException("Already Executed"); executed = true; } captureCallStackTrace(); client.dispatcher().enqueue(new AsyncCall(responseCallback)); }
在构建了一个Runnable的实现类AsyncCall以后,直接调用client.dispatcher().enqueue()方法。
client很明显就是一个OkHttpClient对象,看看它的dispatcher方法:
public Dispatcher dispatcher() { return dispatcher; }
这里其实只是单纯地返回了dispatcher对象,那这个对象是哪里赋予初值的呢?这就要追溯到第1步,构建OkHttpClient对象时,其内部类的Builder的构造方法,部分代码如下:
public Builder() { dispatcher = new Dispatcher(); protocols = DEFAULT_PROTOCOLS; //... }
就在第一行,在创建OkHttpClient对象时,已经实例化好了Dispatcher对象,其构造方法里没有代码,就不贴出来了。接下里我们继续看得到dispatcher以后,调用其enqueue方法的逻辑:
synchronized void enqueue(AsyncCall call) { if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) { runningAsyncCalls.add(call); executorService().execute(call); } else { readyAsyncCalls.add(call); } }
可以看到该方法加了同步锁。并且该方法传递进来了一个Runnable的实现类AsyncCall对象。
这里,首先判断了runningAsyncCalls和runningCallsForHost的个数是否在限制内,如果在,就把传递进来的AsyncCall对象加入到runningAsyncCalls集合中,并调用了executorService().execute(call);去执行call;如果不在限制内,就把AsyncCall对象加入到readyAsyncCalls集合中。
我们来看看上述属性和方法的定义:
private int maxRequests = 64; private int maxRequestsPerHost = 5; /** 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<>(); /** Returns the number of running calls that share a host with {@code call}. */ private int runningCallsForHost(AsyncCall call) { int result = 0; for (AsyncCall c : runningAsyncCalls) { if (c.host().equals(call.host())) result++; } return result; }
可知:
runningAsyncCalls: 正在执行的AsyncCall的个数,包括已经取消了的AsyncCall
readyAsyncCalls:准备执行的AsyncCall的个数
maxRequests:允许正在执行的AsyncCall最大个数,默认64
maxRequestsPerHost:允许每一个Host最多执行的AsyncCall个数
runningCallsForHost(AsyncCall call) :用于计算正在运行的AsyncCall队列中和当前AsyncCall同Host的个数。
上述代码代码到判断逻辑就是:
发起一个网络请求,会先判断当前正在请求的Runnable个数是否小于64,并且当前网络请求host是否小于5个请求,如果是,则把当前AsyncCall加入到正在请求的AsyncCall队列中去,并从通过线程池去执行该AsyncCall;如果不是,则把当前AsyncCall加入到等待的AsyncCall队列中。
这里,我们先看满足if条件时的逻辑,即调用了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; }
注意,该方法用synchronized关键字,保证了ExecutorService为单例模式,这个方法其实就是返回了一个线程池对象,该线程池的创建模式为corePoolSiz为0,而maximumPoolSize为Integer的最大值,即2147483647个,当网络请求特别多的时候,会不会开启特别多的线程,导致手机的开销过大,影响性能呢?其实不会,因为maxRequests已经限制了AsyncCall的个数不能超过64。
如果在自己的项目中,有单独的线程池模版,可以自己实现executorService方法,统一管理线程池。
然后就是调用ExecutorService对象的execute方法,即调用了AsyncCall的run方法:
发现AsyncCall没有run方法的实现,我们去从它的父类NamedRunnable中寻找:
@Override public final void run() { String oldName = Thread.currentThread().getName(); Thread.currentThread().setName(name); try { execute(); } finally { Thread.currentThread().setName(oldName); } }
在NamedRunnable的run方法中,主要调用类execute方法,但是发现NamedRunnable中的execute方法是个抽象方法,继续从其子类AsyncCall中查看execute方法:
@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); } } }
我们主要看主流程:
首先,第4行,调用了getResponseWithInterceptorChain得到了Response对象
然后,第5行,判断一下是否取消了,如果取消了则调用responseCallback.onFailure方法,而responseCallback对象就是第4步call.enqueue(Callback callback)方法的参数callback, 这样就完成当取消了网络请求回调onFailure的流程。
如果没有取消,则在第10行调用responseCallback的onResponse, 这就是我们熟悉的味道了,会把第4行得到的结果当成参数,传递到发起网络请求的地方。
这里已经在子线程中了,也就验证了之前说的回掉onFailure和onResponse方法是在子线程中。
然后,如果请求网络的过程中,进入到了catch块,也是调用onFailure方法,这里就不多说了。
最后,在finally中调用了client.dispatcher().finshed(this),我们来看看Dispatcher中的finished方法:
void finished(AsyncCall call) { finished(runningAsyncCalls, call, true); } 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(); } }
这里的finish方法,主要是把当前AsyncCall从正在运行的AsyncCall任务队列里移除掉。
主流程走完,我们回过头来看AsyncCall中execute的第4行,调用了getResponseWithInterceptorChain方法,这就是真正的网络请求的地方了,实现还是有些复杂的:
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); return chain.proceed(originalRequest); }
首先创建了拦截器Interceptor集合,然后把一堆拦截器加入到集合里,再创建一个RealInterceptorChain对象,它是现实了拦截器Interceptor的内部接口Chain,我们先来看看它的构造方法:
public RealInterceptorChain(List<Interceptor> interceptors, StreamAllocation streamAllocation, HttpCodec httpCodec, RealConnection connection, int index, Request request) { this.interceptors = interceptors; this.connection = connection; this.streamAllocation = streamAllocation; this.httpCodec = httpCodec; this.index = index; this.request = request; }
这里值得注意的就是第1个参数和第5参数,第1个参数是拦截器集合,第5个参数是当前要执行的拦截器在拦截器集合的序号,这里传入的是0,所以接下来会取interceptors的第一个元素,去执行它的方法,后续代码会看到,这里需要知道的就是传入了拦截器集合和需要执行拦截器的序号。
在创建了RealInterceptorChain以后,就调用了它的proceed方法:
@Override public Response proceed(Request request) throws IOException { return proceed(request, streamAllocation, httpCodec, connection); }
这里直接调用了它的重载方法,而后面的三个参数,都是在创建RealInterceptorChain时传入的,这里三个都为null,然后我们继续看看该方法的实现:
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec, RealConnection connection) throws IOException { if (index >= interceptors.size()) throw new AssertionError(); calls++; //省略部分代码... // Call the next interceptor in the chain. RealInterceptorChain next = new RealInterceptorChain( interceptors, streamAllocation, httpCodec, connection, index + 1, request); Interceptor interceptor = interceptors.get(index); Response response = interceptor.intercept(next); //省略部分代码... return response; }
主要看第11行,又创建了一个RealInterceptorChain对象,这里第1个参数还是传入了拦截器集合,但是第5个参数是index+1了,之前是0,所以现在传入的就是1了。然后第12行,这里index 还是为0, 所以就是从拦截器中取出了第一个拦截器,最后再在第13行调用取到的拦截器的intercept方法,进行真正的网络请求,并拿到请求数据Response以后返回。
那么,拦截器集合里的第一个元素是什么呢?我们继续回到之前创建拦截器集合的地方,也就是RealCall的getResponseWithInterceptorChain方法中:
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); return chain.proceed(originalRequest); }
拦截器的第一个元素应该是第三行代码加入的,我们来看看client.interceptors()方法的实现:
/** * Returns an immutable list of interceptors that observe the full span of each call: from before * the connection is established (if any) until after the response source is selected (either the * origin server, cache, or both). */ public List<Interceptor> interceptors() { return interceptors; }
其实就是直接返回了OkHttpClient中的拦截器集合,那它是在哪里赋予初值的呢?其实就在OkHttpClient的构造方法里:
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); //省略部分代码... }
在第6行的地方,调用了Util.immutableList方法,传入了builder的interceptors后,得到了OkHttpClient中的拦截器集合,我们来看看immutableList方法:
/** Returns an immutable copy of {@code list}. */ public static <T> List<T> immutableList(List<T> list) { return Collections.unmodifiableList(new ArrayList<>(list)); }
直接调用了Collections.ummodifiableList方法,这个方法的意义其实就是用于复制一个List的数据,但是复制出来的对象是只读的,不可进行add、remove等修改操作,否则就会报:java.lang.UnsupportedOperationException的错误。
所以,OkHttpClient中的拦截器集合,其实就是通过其内部类Builder中的拦截器集合构造出来的,我们看看Builder的interceptors是哪里初始化的:
public static final class Builder { Dispatcher dispatcher; @Nullable Proxy proxy; List<Protocol> protocols; List<ConnectionSpec> connectionSpecs; final List<Interceptor> interceptors = new ArrayList<>(); //省略部分代码...
第6行,直接创建了拦截器集合,然后我们看看Builder的有参构造方法:
Builder(OkHttpClient okHttpClient) { this.dispatcher = okHttpClient.dispatcher; this.proxy = okHttpClient.proxy; this.protocols = okHttpClient.protocols; this.connectionSpecs = okHttpClient.connectionSpecs; this.interceptors.addAll(okHttpClient.interceptors); //省略部分代码... }
第6行代码,这里把OkHttpClient的拦截器集合加入到Builder的拦截器集合中,但是我们之前在第1步创建OkHttpClient对象时讲到,先是调用了Builder无参的构造方法,初始化了参数以后,才通过Builder对象,去初始化OkHttpClient对象,所以,根本没有调用上述Builder有参构造方法,即OkHttpClient的默认拦截器集合为一个空数组。
我们再回到RealCall的getResponseWithInterceptorChain方法:
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); return chain.proceed(originalRequest); }
既然client.interceptors默认是空数组,我们来看看第5行的retryAndFollowUpInterceptor会是第一个拦截器么?
我们先说一下结论,其实retryAndFollowUpInterceptor就是第一个拦截器,然后第10行的client.networkInterceptors()的赋值流程和client.interceptors()是一致的,所以最后的值都为size为0的ArrayList。那么传入到RealInterceptorChain的拦截器集合就是加入了以下5个拦截器:
1.RetryAndFollowUpInterceptor
2.BridgeInterceptor
3.CacheInterceptor
4.ConnectInterceptor
5.CallServerInterceptor
然后通过调用这5个拦截器的intercept方法,完成各自的功能。
那我们先来看第一个拦截器RetryAndFollowUpInterceptor初始化的地方:
RealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) { final EventListener.Factory eventListenerFactory = client.eventListenerFactory(); this.client = client; this.originalRequest = originalRequest; this.forWebSocket = forWebSocket; this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client, forWebSocket); // TODO(jwilson): this is unsafe publication and not threadsafe. this.eventListener = eventListenerFactory.create(this); }
在RealCall的构造方法里的第7行,初始化了retryAndFollowUpInterceptor,它是一个RetryAndFollowUpInterceptor对象,而RealCall的构造方法是在第3步,OkHttpClient调用newCall方法时调用的,所以也验证了retryAndFollowUpInterceptor就是RealCall中拦截器的第一个元素。
然后我们回到主流程,得到了第一个拦截器以后,会调用其intercept方法,并把一个新的RealInterceptorChain对象传递进去,我们先看看RetryAndFollowUpInterceptor中的intercept方法:
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); RealInterceptorChain realChain = (RealInterceptorChain) chain; Call call = realChain.call(); EventListener eventListener = realChain.eventListener(); streamAllocation = new StreamAllocation(client.connectionPool(), createAddress(request.url()), call, eventListener, callStackTrace); int followUpCount = 0; Response priorResponse = null; while (true) { if (canceled) { streamAllocation.release(); throw new IOException("Canceled"); } Response response = null; boolean releaseConnection = true; try { response = realChain.proceed(request, streamAllocation, null, null); releaseConnection = false; } catch (RouteException e) { // The attempt to connect via a route failed. The request will not have been sent. if (!recover(e.getLastConnectException(), false, request)) { throw e.getLastConnectException(); } releaseConnection = false; continue; } catch (IOException e) { // An attempt to communicate with a server failed. The request may have been sent. boolean requestSendStarted = !(e instanceof ConnectionShutdownException); if (!recover(e, requestSendStarted, request)) throw e; releaseConnection = false; continue; } finally { // We're throwing an unchecked exception. Release any resources. if (releaseConnection) { streamAllocation.streamFailed(null); streamAllocation.release(); } } // Attach the prior response if it exists. Such responses never have a body. if (priorResponse != null) { response = response.newBuilder() .priorResponse(priorResponse.newBuilder() .body(null) .build()) .build(); } Request followUp = followUpRequest(response); if (followUp == null) { if (!forWebSocket) { streamAllocation.release(); } return response; } closeQuietly(response.body()); if (++followUpCount > MAX_FOLLOW_UPS) { streamAllocation.release(); throw new ProtocolException("Too many follow-up requests: " + followUpCount); } if (followUp.body() instanceof UnrepeatableRequestBody) { streamAllocation.release(); throw new HttpRetryException("Cannot retry streamed HTTP body", response.code()); } if (!sameConnection(response, followUp.url())) { streamAllocation.release(); streamAllocation = new StreamAllocation(client.connectionPool(), createAddress(followUp.url()), call, eventListener, callStackTrace); } else if (streamAllocation.codec() != null) { throw new IllegalStateException("Closing the body of " + response + " didn't close its backing stream. Bad interceptor?"); } request = followUp; priorResponse = response; } }
首先,在第7行的地方,创建了一个StreamAllocation对象。然后在第12行,写了一个while(true)的循环,其实当一次性请求成功时,while里面的代码块只会执行一次,得到Response结果以后,直接return了,所以我们先不用纠结这个while(true)。继续往下看,第21行代码处,调用了realChain.proceed方法,而这个realChain对象,就是在取出拦截器集合里第一个元素RetryAndFollowUpInterceptor对象以后,调用intercept时传递进来的参数RealInterceptorChain对象,还记得当时创建时,构造参数传递的第5个参数为index+1么?也就是这时的realChain的index=1。
这里有些难理解,总体来说就是:
1.首先,创建了一系列的拦截器
2.然后创建了一个RealInterceptorChain对象,调用了它的proceed方法,并告知取拦截器的序号
3.在proceed方法里,从拦截器集合里,取出对应序号的拦截器,然后调用拦截器的intercept方法
4.在intercept方法里,继续调用RealInterceptorChain的proceed方法
5.一直循环3-4,直到取到最后一个拦截器CallServerInterceptor,并返回网络请求的结果Response。
如图:
那我们继续看RealInterceptorChain的proceed方法,就是上述流程的第4步:
这时候取出的就是第2个拦截器BridgeInterceptor对象,然后我们看看它的intercept方法:
@Override public Response intercept(Chain chain) throws IOException { Request userRequest = chain.request(); Request.Builder requestBuilder = userRequest.newBuilder(); RequestBody body = userRequest.body(); if (body != null) { MediaType contentType = body.contentType(); if (contentType != null) { requestBuilder.header("Content-Type", contentType.toString()); } long contentLength = body.contentLength(); if (contentLength != -1) { requestBuilder.header("Content-Length", Long.toString(contentLength)); requestBuilder.removeHeader("Transfer-Encoding"); } else { requestBuilder.header("Transfer-Encoding", "chunked"); requestBuilder.removeHeader("Content-Length"); } } if (userRequest.header("Host") == null) { requestBuilder.header("Host", hostHeader(userRequest.url(), false)); } if (userRequest.header("Connection") == null) { requestBuilder.header("Connection", "Keep-Alive"); } // If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing // the transfer stream. boolean transparentGzip = false; if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) { transparentGzip = true; requestBuilder.header("Accept-Encoding", "gzip"); } List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url()); if (!cookies.isEmpty()) { requestBuilder.header("Cookie", cookieHeader(cookies)); } if (userRequest.header("User-Agent") == null) { //requestBuilder.header("User-Agent", Version.userAgent()); } Response networkResponse = chain.proceed(requestBuilder.build()); 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); responseBuilder.body(new RealResponseBody(strippedHeaders, Okio.buffer(responseBody))); } return responseBuilder.build(); }
可以看到,这个方法主要是处理了网络请求头的问题,包括文本类型、Host、User-Agent、Keep-Alive等配置。这里主要看47行,这里继续调用了RealInterceptorChain的peroceed方法,不过这里的方法参数Request已经是封装过Request了。
根据之前讲到的,我们很容易想到,这时候应该是取第3个拦截器CacheInterceptor,并执行它的intercept方法,我们来看看这个方法:
@Override public Response intercept(Chain chain) throws IOException { Response cacheCandidate = cache != null ? cache.get(chain.request()) : null; long now = System.currentTimeMillis(); CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get(); Request networkRequest = strategy.networkRequest; Response cacheResponse = strategy.cacheResponse; if (cache != null) { cache.trackResponse(strategy); } if (cacheCandidate != null && cacheResponse == null) { closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it. } // If we're forbidden from using the network and the cache is insufficient, fail. if (networkRequest == null && cacheResponse == null) { return new Response.Builder() .request(chain.request()) .protocol(Protocol.HTTP_1_1) .code(504) .message("Unsatisfiable Request (only-if-cached)") .body(Util.EMPTY_RESPONSE) .sentRequestAtMillis(-1L) .receivedResponseAtMillis(System.currentTimeMillis()) .build(); } // If we don't need the network, we're done. if (networkRequest == null) { return cacheResponse.newBuilder() .cacheResponse(stripBody(cacheResponse)) .build(); } Response networkResponse = null; try { networkResponse = chain.proceed(networkRequest); } finally { // If we're crashing on I/O or otherwise, don't leak the cache body. if (networkResponse == null && cacheCandidate != null) { closeQuietly(cacheCandidate.body()); } } // If we have a cache response too, then we're doing a conditional get. if (cacheResponse != null) { if (networkResponse.code() == HTTP_NOT_MODIFIED) { Response response = cacheResponse.newBuilder() .headers(combine(cacheResponse.headers(), networkResponse.headers())) .sentRequestAtMillis(networkResponse.sentRequestAtMillis()) .receivedResponseAtMillis(networkResponse.receivedResponseAtMillis()) .cacheResponse(stripBody(cacheResponse)) .networkResponse(stripBody(networkResponse)) .build(); networkResponse.body().close(); // Update the cache after combining headers but before stripping the // Content-Encoding header (as performed by initContentStream()). cache.trackConditionalCacheHit(); cache.update(cacheResponse, response); return response; } else { closeQuietly(cacheResponse.body()); } } Response response = networkResponse.newBuilder() .cacheResponse(stripBody(cacheResponse)) .networkResponse(stripBody(networkResponse)) .build(); if (cache != null) { if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) { // Offer this request to the cache. CacheRequest cacheRequest = cache.put(response); return cacheWritingResponse(cacheRequest, response); } if (HttpMethod.invalidatesCache(networkRequest.method())) { try { cache.remove(networkRequest); } catch (IOException ignored) { // The cache cannot be written. } } } return response; }
看名称就知道了,这显然是一个处理缓存相关的拦截器。我们直接看核心代码,就是第42行,这里继续调用了chain.proceed方法,通过调用下一个拦截器的intercept方法得到请求网络结果networkResponse,然后在第72行通过返回的结果,构造Response出对象,并返回。
而下一个拦截器就是ConnectInterceptor,我们来看看它的intercept方法:
@Override public Response intercept(Chain chain) throws IOException { RealInterceptorChain realChain = (RealInterceptorChain) chain; Request request = realChain.request(); StreamAllocation streamAllocation = realChain.streamAllocation(); // We need the network to satisfy this request. Possibly for validating a conditional GET. boolean doExtensiveHealthChecks = !request.method().equals("GET"); HttpCodec httpCodec = streamAllocation.newStream(client, doExtensiveHealthChecks); RealConnection connection = streamAllocation.connection(); return realChain.proceed(request, streamAllocation, httpCodec, connection); }
容易看出ConnectInterceptor就是一个建立网络连接的拦截器,第9行代码处,就是得到了一个网络链接RealConnection,就像HttpUrlConnection中的new URL().openConnection()一样,然后在第11行,调用了realChain.proceed方法,并把刚才得到RealConnection对象传递进去,这里很容易推测,最后一个拦截器的作用应该就是做真正的网络请求。
下一个拦截器,也是最后一个拦截器,就是CallServerInterceptor,我们来看看它的intercept方法:
@Override public Response intercept(Chain chain) throws IOException { RealInterceptorChain realChain = (RealInterceptorChain) chain; HttpCodec httpCodec = realChain.httpStream(); StreamAllocation streamAllocation = realChain.streamAllocation(); RealConnection connection = (RealConnection) realChain.connection(); Request request = realChain.request(); long sentRequestMillis = System.currentTimeMillis(); httpCodec.writeRequestHeaders(request); Response.Builder responseBuilder = null; if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) { // If there's a "Expect: 100-continue" header on the request, wait for a "HTTP/1.1 100 // Continue" response before transmitting the request body. If we don't get that, return what // we did get (such as a 4xx response) without ever transmitting the request body. if ("100-continue".equalsIgnoreCase(request.header("Expect"))) { httpCodec.flushRequest(); responseBuilder = httpCodec.readResponseHeaders(true); } if (responseBuilder == null) { // Write the request body if the "Expect: 100-continue" expectation was met. Sink requestBodyOut = httpCodec.createRequestBody(request, request.body().contentLength()); BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut); request.body().writeTo(bufferedRequestBody); bufferedRequestBody.close(); } else if (!connection.isMultiplexed()) { // If the "Expect: 100-continue" expectation wasn't met, prevent the HTTP/1 connection from // being reused. Otherwise we're still obligated to transmit the request body to leave the // connection in a consistent state. streamAllocation.noNewStreams(); } } httpCodec.finishRequest(); if (responseBuilder == null) { responseBuilder = httpCodec.readResponseHeaders(false); } Response response = responseBuilder .request(request) .handshake(streamAllocation.connection().handshake()) .sentRequestAtMillis(sentRequestMillis) .receivedResponseAtMillis(System.currentTimeMillis()) .build(); int code = response.code(); if (forWebSocket && code == 101) { // Connection is upgrading, but we need to ensure interceptors see a non-null response body. response = response.newBuilder() .body(Util.EMPTY_RESPONSE) .build(); } else { response = response.newBuilder() .body(httpCodec.openResponseBody(response)) .build(); } if ("close".equalsIgnoreCase(response.request().header("Connection")) || "close".equalsIgnoreCase(response.header("Connection"))) { streamAllocation.noNewStreams(); } if ((code == 204 || code == 205) && response.body().contentLength() > 0) { throw new ProtocolException( "HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength()); } return response; }
我们先看第9行,直接通过调用了httpCodec.writeRequestHeaders方法把请求头写入,而httpCodec其实是在ConnectInterceptor的intercept方法中创建的,它其实是个Http1Codec对象。如果是post请求并且有请求body,则会执行第23行代码去调用httpCodec.createRequestBody去构建请求body,并写入。这里为Get请求,所以不会执行这段代码。继续往下看,第35行调用了httpCodec的finishRequest方法,其实就是flush了一把,用于请求数据写入完成。然后第38行,通过httpCodec的readResponseHeaders方法得到ResponseBuilder对象,然后再在第41行,去得到Response对象,最后,在55行去调用httpCodec.openResponseBody方法,构造出最后的Response并返回。
这样就完成了所有拦截器的流程,然后就逐级返回把这个Response给到Callback的回调方法onResponse。
整个流程,可能就是拦截器的部分复杂一些,不过也是OkHttp的精髓所在,把不同的功能拆分成不同的拦截器来实现。我们总结下这5个拦截器的功能:
1.RetryAndFollowUpInterceptor:处理失败、转发等网络请求
2.BridgeInterceptor:处理请求头
3.CacheInterceptor:处理缓存相关的逻辑
4.ConnectInterceptor:构造网络连接
5.CallServerInterceptor:真正网络请求,并得到Response最后返回
我们会发现,这5个拦截器的排序也是恰到好处。
最后,一图抵千言:
总结:
这篇博客主要是对OkHttp一次简单的Get请求的源码分析,还有很多细节性的地方没有涉及到,后面会写一篇OkHttp实现细节的的博客。
欢迎交流、指正。
- OkHttp源码分析
- OkHttp源码分析
- OkHttp源码分析
- OKHttp源码分析
- OkHttp源码分析
- OKHttp源码分析
- okhttp源码分析
- OkHttp源码分析
- Okhttp使用和源码分析三(OkHttp源码分析)
- OKHttp框架源码分析(一)
- OKHttp源码分析1 - 框架
- OKHttp源码分析(一)
- Okhttp文件上传源码分析
- OkHttp源码分析(一)
- okhttp源码的简单分析
- Rxjava+retrofit+okhttp源码分析
- okhttp网络框架源码分析
- 网络框架okHttp源码分析
- HDU 1796 How many integers can you find【容斥原理】
- Centos5.5 IDT HOOK
- Python交互环境下如何输入代码
- php搭建环境
- Nginx反向代理以伪装站点登录
- OkHttp源码分析
- iOS/Swift3.0 终端命令自动打包
- Maven实践---导航
- Android InputMonitor
- StructuredStreaming官方文档翻译
- TCP/IP协议、socket及socket简单实现网络通讯
- php mysql数据库操作类
- socket之UDP通信
- HBase的RowKey设计原则