首先先看一张流程图,该图是从拆轮子系列:拆 OkHttp 中盗来的,以下:
在上一篇博客深刻理解OkHttp源码(一)——提交请求中介绍到了getResponseWithInterceptorChain()方法,本篇主要从这儿继续往下讲解。前端
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的interceptor()方法获取全部应用拦截器,而后再加上RetryAndFollwoUpInterceptor、BridgeInterceptor、CacheInterceptor、ConnectInterceptor、若是不是WebSocket,还须要加上OkHttpClient的网络拦截器,最后再加上CallServerInterceptor,而后构造一个RealInterceptorChain对象,该类是拦截器链的具体实现,携带整个拦截器链,包含全部应用拦截器、OkHttp核心、全部网络拦截器和最终的网络调用者。
OkHttp的这种拦截器链采用的是责任链模式,这样的好处是将请求的发送和处理分开,而且能够动态添加中间的处理方实现对请求的处理、短路等操做。 java
下面是RealInterceptorChain的定义,该类实现了Chain接口,在getResponseWithInterceptorChain调用时好几个参数都传的null,具体是StreamAllocation、HttpStream和Connection;其他的参数中index表明当前拦截器列表中的拦截器的索引。缓存
/** * A concrete interceptor chain that carries the entire interceptor chain: all application * interceptors, the OkHttp core, all network interceptors, and finally the network caller. */ public final class RealInterceptorChain implements Interceptor.Chain { private final List<Interceptor> interceptors; private final StreamAllocation streamAllocation; private final HttpStream httpStream; private final Connection connection; private final int index; private final Request request; private int calls; public RealInterceptorChain(List<Interceptor> interceptors, StreamAllocation streamAllocation, HttpStream httpStream, Connection connection, int index, Request request) { this.interceptors = interceptors; this.connection = connection; this.streamAllocation = streamAllocation; this.httpStream = httpStream; this.index = index; this.request = request; } @Override public Connection connection() { return connection; } public StreamAllocation streamAllocation() { return streamAllocation; } public HttpStream httpStream() { return httpStream; } @Override public Request request() { return request; } @Override public Response proceed(Request request) throws IOException { return proceed(request, streamAllocation, httpStream, connection); } public Response proceed(Request request, StreamAllocation streamAllocation, HttpStream httpStream, Connection connection) throws IOException { if (index >= interceptors.size()) throw new AssertionError(); calls++; // If we already have a stream, confirm that the incoming request will use it. if (this.httpStream != null && !sameConnection(request.url())) { throw new IllegalStateException("network interceptor " + interceptors.get(index - 1) + " must retain the same host and port"); } // If we already have a stream, confirm that this is the only call to chain.proceed(). if (this.httpStream != null && calls > 1) { throw new IllegalStateException("network interceptor " + interceptors.get(index - 1) + " must call proceed() exactly once"); } //调用拦截器链中余下的进行处理获得响应 // Call the next interceptor in the chain. RealInterceptorChain next = new RealInterceptorChain( interceptors, streamAllocation, httpStream, connection, index + 1, request); Interceptor interceptor = interceptors.get(index); Response response = interceptor.intercept(next); // Confirm that the next interceptor made its required call to chain.proceed(). if (httpStream != null && index + 1 < interceptors.size() && next.calls != 1) { throw new IllegalStateException("network interceptor " + interceptor + " must call proceed() exactly once"); } // Confirm that the intercepted response isn't null. if (response == null) { throw new NullPointerException("interceptor " + interceptor + " returned null"); } return response; } private boolean sameConnection(HttpUrl url) { return url.host().equals(connection.route().address().url().host()) && url.port() == connection.route().address().url().port(); } }
主要看proceed方法,该方法是具体根据请求获取响应的实现。由于一开始httpStream为null,因此前面的判断都无效,直接进入第92行,首先建立next拦截器链,主须要把索引置为index+1便可;而后获取第一个拦截器,调用其intercept方法。
如今假设没有添加应用拦截器和网络拦截器,那么这第一个拦截器将会是RetryAndFollowUpInterceptor。 服务器
RetryAndFollowUpInterceptor拦截器会从错误中恢复以及重定向。若是Call被取消了,那么将会抛出IoException。下面是其intercept方法实现:cookie
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); streamAllocation = new StreamAllocation( client.connectionPool(), createAddress(request.url())); int followUpCount = 0; Response priorResponse = null; while (true) { //若是取消了,那么释放流以及抛出异常 if (canceled) { streamAllocation.release(); throw new IOException("Canceled"); } Response response = null; boolean releaseConnection = true; try { //调用拦截器链余下的获得响应 response = ((RealInterceptorChain) chain).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(), true, request)) throw e.getLastConnectException(); releaseConnection = false; continue; } catch (IOException e) { // An attempt to communicate with a server failed. The request may have been sent. if (!recover(e, false, 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) { 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())); } else if (streamAllocation.stream() != null) { throw new IllegalStateException("Closing the body of " + response + " didn't close its backing stream. Bad interceptor?"); } request = followUp; priorResponse = response; } }
从上面的代码能够看出,建立了streamAllocation对象,streamAllocation负责为链接分配流,接下来调用传进来的chain参数继续获取响应,能够看到若是获取失败了,在各个异常中都会调用recover方法尝试恢复请求,从响应中取出followUp请求,若是有就检查followUpCount,若是符合要求而且有followUp请求,那么须要继续进入while循环,若是没有,则直接返回响应了。首先不考虑有后续请求的状况,那么接下来调用的将会是BridgeInterceptor。网络
BridgeInterceptor从用户的请求构建网络请求,而后提交给网络,最后从网络响应中提取出用户响应。从最上面的图能够看出,BridgeInterceptor实现了适配的功能。下面是其intercept方法:app
@Override public Response intercept(Chain chain) throws IOException { Request userRequest = chain.request(); Request.Builder requestBuilder = userRequest.newBuilder(); RequestBody body = userRequest.body(); //若是存在请求主体部分,那么须要添加Content-Type、Content-Length首部 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)); } //OkHttp默认使用HTTP持久链接 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) { 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、Connection、Accept-Encoding参数等,而后根据看是否须要填充Cookie,在对原始请求作出处理后,使用chain的procced方法获得响应,接下来对响应作处理获得用户响应,最后返回响应。接下来再看下一个拦截器CacheInterceptor的处理。异步
CacheInterceptor尝试从缓存中获取响应,若是能够获取到,则直接返回;不然将进行网络操做获取响应。CacheInterceptor使用OkHttpClient的internalCache方法的返回值做为参数。下面先看internalCache方法:ide
InternalCache internalCache() {
return cache != null ? cache.internalCache : internalCache; }
而Cache和InternalCache都是OkHttpClient.Builder中能够设置的,而其设置会互相抵消,代码以下:ui
/** Sets the response cache to be used to read and write cached responses. */ void setInternalCache(InternalCache internalCache) { this.internalCache = internalCache; this.cache = null; } public Builder cache(Cache cache) { this.cache = cache; this.internalCache = null; return this; }
默认的,若是没有对Builder进行缓存设置,那么cache和internalCache都为null,那么传入到CacheInterceptor中的也是null,下面是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. } //不适用网络响应,可是缓存中没有缓存响应,返回504错误 // 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(EMPTY_BODY) .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 (validate(cacheResponse, networkResponse)) { Response response = cacheResponse.newBuilder() .headers(combine(cacheResponse.headers(), networkResponse.headers())) .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 (HttpHeaders.hasBody(response)) { CacheRequest cacheRequest = maybeCache(response, networkResponse.request(), cache); response = cacheWritingResponse(cacheRequest, response); } return response; }
从上面的代码能够看出,首先尝试从缓存中根据请求取出相应,而后建立CacheStrategy对象,该对象有两个字段networkRequest和cahceResponse,其中networkRequest不为null则表示须要进行网络请求,cacheResponse表示返回的或须要更新的缓存响应,为null则表示请求没有使用缓存。下面是对这两个字段的不一样取值返回不一样的响应:
1. networkRequest\==null&& cacheResponse==null:表示该请求不须要使用网络可是缓存响应不存在,则返回504错误的响应;
2. networkRequest\==null&&cacheRequest!=null:表示该请求不容许使用网络,可是由于有缓存响应的存在,因此直接返回缓存响应
3. networkRequest!=null:表示该请求强制使用网络,则调用拦截器链中其他的拦截器继续处理获得networkResponse,获得网络响应后,又分为两种状况处理:
1)cacheResponse!=null: 缓存响应以前存在,若是以前的缓存还有效的话,那么须要更新缓存,返回组合后的响应
2)cacheResponse==null: 以前没有缓存响应,则将组合后的响应直接写入缓存便可。
下面继续看若是networkRequest为null的状况,那么须要继续调用拦截器链,那么下一个拦截器是ConnectInterceptor。
打开一个到目标服务器的链接。intercept方法的实现以下:
public Response intercept(Chain chain) throws IOException { RealInterceptorChain realChain = (RealInterceptorChain) chain; Request request = realChain.request(); StreamAllocation streamAllocation = realChain.streamAllocation(); //建立具体的Socket链接,传入proceed中的后两个参数再也不为null // We need the network to satisfy this request. Possibly for validating a conditional GET. boolean doExtensiveHealthChecks = !request.method().equals("GET"); HttpStream httpStream = streamAllocation.newStream(client, doExtensiveHealthChecks); RealConnection connection = streamAllocation.connection(); return realChain.proceed(request, streamAllocation, httpStream, connection); }
在RetryAndFollowUpInterceptor中,建立了StreamAllocation并将其传给了后面的拦截器链,因此这儿获得的StreamAllocation就是那时传入的,接下来是获取HttpStream对象以及RealConnection对象,而后继续交给下面的拦截器处理,至此,下一个拦截器中proceed中的后三个参数均不为null了。其中HttpStream接口能够认为是该链接的输入输出流,能够从中读响应,也能够写请求数据。
在看最后一个拦截器以前,咱们再看一次RealInterceptorChain的proceed方法,由于此时的HttpStream和Connection均不为null。下面是proceed方法的实现:
public Response proceed(Request request, StreamAllocation streamAllocation, HttpStream httpStream, Connection connection) throws IOException { if (index >= interceptors.size()) throw new AssertionError(); calls++; // If we already have a stream, confirm that the incoming request will use it. if (this.httpStream != null && !sameConnection(request.url())) { throw new IllegalStateException("network interceptor " + interceptors.get(index - 1) + " must retain the same host and port"); } // If we already have a stream, confirm that this is the only call to chain.proceed(). if (this.httpStream != null && calls > 1) { throw new IllegalStateException("network interceptor " + interceptors.get(index - 1) + " must call proceed() exactly once"); } // Call the next interceptor in the chain. RealInterceptorChain next = new RealInterceptorChain( interceptors, streamAllocation, httpStream, connection, index + 1, request); Interceptor interceptor = interceptors.get(index); Response response = interceptor.intercept(next); // Confirm that the next interceptor made its required call to chain.proceed(). if (httpStream != null && index + 1 < interceptors.size() && next.calls != 1) { throw new IllegalStateException("network interceptor " + interceptor + " must call proceed() exactly once"); } // Confirm that the intercepted response isn't null. if (response == null) { throw new NullPointerException("interceptor " + interceptor + " returned null"); } return response; }
从上面的代码能够能够看出,调用sameConnection方法比较这是请求的URL与初始的是否相同,若是不一样,则直接异常,由于相同的主机和端口对应的链接能够重用,而ConnectInterceptor已经建立好了Connection,因此这时若是URL主机和端口不匹配的话,不会再建立新的Connection而是直接抛出异常。这就说明网络拦截器中不能够将请求修改为与原始请求不一样的主机和端口,不然就会抛出异常。其次,每一个网络拦截器只能调用一次proceed方法,若是调用两次或以上次数,就会抛出异常。
在处理完网络拦截器后,会调用最后一个拦截器CallServerInterceptor。
CallServerInterceptor是拦截器链中最后一个拦截器,负责将网络请求提交给服务器。它的intercept方法实现以下:
@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(); } //若是服务端不支持持久链接 if ("close".equalsIgnoreCase(response.request().header("Connection")) || "close".equalsIgnoreCase(response.header("Connection"))) { streamAllocation.noNewStreams(); } int code = response.code(); if ((code == 204 || code == 205) && response.body().contentLength() > 0) { throw new ProtocolException( "HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength()); } return response; }
从上面的代码中能够看出,首先获取HttpStream对象,而后调用writeRequestHeaders方法写入请求的头部,而后判断是否须要写入请求的body部分,最后调用finishRequest()方法将全部数据刷新给底层的Socket,接下来尝试调用readResponseHeaders()方法读取响应的头部,而后再调用openResponseBody()方法获得响应的body部分,最后返回响应。
能够看到CallServerInterceptor完成了最终的发送请求和接受响应。至此,整个拦截器链就分析完了,而获得原始响应后,前面的拦截器又分别作了不一样的处理,ConnectInterceptor没有对响应进入处理,CacheInterceptor根据请求的缓存控制判断是否须要将响应放入缓存或更新缓存,BridgeInterceptor将响应去除部分头部信息获得用户的响应,RetryAndFollowUpInterceptor根据响应中是否须要重定向判断是否须要进行新一轮的请求。
在这边咱们须要明白一点,OkHttp的底层是经过Java的Socket发送HTTP请求与接受响应的(这也好理解,HTTP就是基于TCP协议的),可是OkHttp实现了链接池的概念,即对于同一主机的多个请求,其实能够公用一个Socket链接,而不是每次发送完HTTP请求就关闭底层的Socket,这样就实现了链接池的概念。而OkHttp对Socket的读写操做使用的OkIo库进行了一层封装。
在上面分析完OkHttp默认的整个拦截器链的工做流程后,再来看若是添加了应用拦截器或网络拦截器后,是怎样的一个效果?
在上面的代码分析中,应用拦截器是位于RetryAndFollowUpInterceptor以前,即拦截器链的最前端;网络拦截器位于CallServerInterceptor以前,即正在进行网络以前。因此能够更深刻地理解使用OkHttp进行网络同步和异步操做中应用拦截器和网络拦截器的区别,这儿再详细解释一下。
拦截器在拦截器链中位置越靠前,那么对请求的处理是越靠前,可是对响应的处理确实靠后的,明白这一点,那么进行拦截器链的分析就会简单不少