本篇文章主要介绍OkHttp的默认拦截器
- 重试拦截器
- 桥接拦截器
- 缓存拦截器
- 连接拦截器
- 访问服务器拦截器
通过拦截器将OkHttp的访问网络的过程进行分解,每个拦截器专司其职. 所有的拦截器都实现了Interceptor接口
public interface Interceptor {
Response intercept(Chain chain) throws IOException;
interface Chain {
Request request();
Response proceed(Request request) throws IOException;
Connection connection();
}
}
好了,下面我们看看这些拦截器都做了什么,由上面的接口我们只用关心 Response proceed(Request request) throws IOException方法
一,重试拦截器RetryAndFollowUpInterceptor
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
streamAllocation = new StreamAllocation(
client.connectionPool(), createAddress(request.url()), 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 = ((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(), false, request)) {
throw e.getLastConnectException();
}
releaseConnection = false;
Log.i("xxx","retry "+e.toString() );
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;
Log.i("xxx","retry io "+e.toString() );
continue;
} finally {
Log.i("xxx","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()), 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;
}
}
1,和Volley的重试机制类似, 首先开启一个死循环while(true)
当没有获取到响应且出现的异常是可以重试的, 他将一直重试
2,接下来会判断是否取消,如果取消,则直接抛出异常,然后在AsyncCall的execute方法中直接回调失败的方法 responseCallback.onFailure(RealCall.this, e);
3,通过response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
递归调用下一个拦截器获取response
如果出现异常则通过recover函数判断是否可以继续重试
否则继续向下执行.
下面看下recover函数, 里面列举了四种况下是不能重试
private boolean recover(IOException e, boolean requestSendStarted, Request userRequest) {
streamAllocation.streamFailed(e);
// The application layer has forbidden retries.
if (!client.retryOnConnectionFailure()) return false;
// We can't send the request body again.
if (requestSendStarted && userRequest.body() instanceof UnrepeatableRequestBody) return false;
// This exception is fatal.
if (!isRecoverable(e, requestSendStarted)) return false;
// No more routes to attempt.
if (!streamAllocation.hasMoreRoutes()) return false;
// For failure recovery, use the same route selector with a new connection.
return true;
}
A,设置了禁止重试
B,重复发送请求体
C,出现了一些严重的错误,不能进一步重试
这些严重的错误在isRecoverable方法中的if判断中提现
例如,协议错误,中断,连接超时,SSL握手错误等等
private boolean isRecoverable(IOException e, boolean requestSendStarted) {
// If there was a protocol problem, don't recover.
if (e instanceof ProtocolException) {
return false;
}
// If there was an interruption don't recover, but if there was a timeout connecting to a route
// we should try the next route (if there is one).
if (e instanceof InterruptedIOException) {
return e instanceof SocketTimeoutException && !requestSendStarted;
}
// Look for known client-side or negotiation errors that are unlikely to be fixed by trying
// again with a different route.
if (e instanceof SSLHandshakeException) {
// If the problem was a CertificateException from the X509TrustManager,
// do not retry.
if (e.getCause() instanceof CertificateException) {
return false;
}
}
if (e instanceof SSLPeerUnverifiedException) {
// e.g. a certificate pinning error.
return false;
}
// An example of one we might want to retry with a different route is a problem connecting to a
// proxy and would manifest as a standard IOException. Unless it is one we know we should not
// retry, we return true and try a new route.
return true;
}
D,没有更多的路由线路来尝试
4,当顺利的得到Response响应以后,会通过 Request followUp = followUpRequest(response);来判断是否存在重定向
如果存在,则通过新的followUp来进行再次访问,本次得到的响应存放在priorResponse中,然后继续在这个死循环While(true)中再次发出请求. 对于这个重定向处理,Volley中默认是没有的
如果不存在,followUp那么为空,直接返回Response对象到上一个拦截器
二,桥接拦截器 BridgeInterceptor
桥接拦截器BridgeInterceptor比较简单,主要干两件事儿
- 在递归调用下一个拦截器获取Response后,构造Request的请求头
- 在得到响应Reponse后,构造Response的响应头
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", "sss");
// 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();
}
上面在构造请求头的时候,值得注意的是,Content-Encoding和Content-Length不能同时出现.
- Content-Length如果存在并且有效的话,则必须和消息内容的传输长度完全一致。如果过短则会截断,过长则会导致超时。
- HTTP1.1必须支持chunk模式。因为当不确定消息长度的时候,可以通过chunk机制来处理这种情况,也就是分块传输。
三,缓存拦截器 CacheInterceptor
如果想比较好的理解缓存拦截器, 要对Http缓存机制有所了解, 特别是涉及到的请求和响应的请求头
包括控制缓存时间的 Cache-Control , Expires
以及缓存服务器再验证的 If-Modify-Since, If-None-Match
和缓存新鲜度的,no-cache, no-store, max-age , if-only-cache等
可以参考这篇文章
下面先贴出核心代码
@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 (HttpHeaders.hasBody(response)) {
CacheRequest cacheRequest = maybeCache(response, networkResponse.request(), cache);
response = cacheWritingResponse(cacheRequest, response);
}
return response;
}
1,首先根据Request的url从缓存中获取缓存cacheCandidate
2,根据请求Request和从缓存中获取的cacheCandidate(可能为空)来构造缓存策略CacheStrategy,下面看下是怎么构造的
A,首先构造Factory对象
public Factory(long nowMillis, Request request, Response cacheResponse) {
... ...
Headers headers = cacheResponse.headers();
for (int i = 0, size = headers.size(); i < size; i++) {
String fieldName = headers.name(i);
String value = headers.value(i);
if ("Date".equalsIgnoreCase(fieldName)) {
servedDate = HttpDate.parse(value);
servedDateString = value;
} else if ("Expires".equalsIgnoreCase(fieldName)) {
expires = HttpDate.parse(value);
} else if ("Last-Modified".equalsIgnoreCase(fieldName)) {
lastModified = HttpDate.parse(value);
lastModifiedString = value;
} else if ("ETag".equalsIgnoreCase(fieldName)) {
etag = value;
} else if ("Age".equalsIgnoreCase(fieldName)) {
ageSeconds = HttpHeaders.parseSeconds(value, -1);
}
}
}
}
当后去的缓存响应不为空时,主要获取这个响应的头信息
Date, Expires Last-Modified ETag等信息,这些字段是用来判断缓存是否过期,以及缓存验证的
B,接下来获取缓存策略
public CacheStrategy get() {
CacheStrategy candidate = getCandidate();
if (candidate.networkRequest != null && request.cacheControl().onlyIfCached()) {
// We're forbidden from using the network and the cache is insufficient.
return new CacheStrategy(null, null);
}
return candidate;
}
private CacheStrategy getCandidate() {
if (cacheResponse == null) {
return new CacheStrategy(request, null);
}
if (request.isHttps() && cacheResponse.handshake() == null) {
return new CacheStrategy(request, null);
}
... ....
String conditionName;
String conditionValue;
if (etag != null) {
conditionName = "If-None-Match";
conditionValue = etag;
} else if (lastModified != null) {
conditionName = "If-Modified-Since";
conditionValue = lastModifiedString;
} else if (servedDate != null) {
conditionName = "If-Modified-Since";
conditionValue = servedDateString;
} else {
return new CacheStrategy(request, null); // No condition! Make a regular request.
}
Headers.Builder conditionalRequestHeaders = request.headers().newBuilder();
Internal.instance.addLenient(conditionalRequestHeaders, conditionName, conditionValue);
Request conditionalRequest = request.newBuilder()
.headers(conditionalRequestHeaders.build())
.build();
return new CacheStrategy(conditionalRequest, cacheResponse);
}
getCandidate是获取缓存策略的核心
主要两部分内容
1)不使用缓存,直接return new CacheStrategy(request, null);
2)使用缓存
- 缓存不过期,直接返回Response
- 缓存过期,使用If-None-Match与ETag或者If-Modified-Since与Last-Modify对缓存进行验证.
3,我们再将目光回到CacheInterceptor的intercept方法
得到缓存策略CacheStrategy后
进行一系列判断
1)如果CacheStrategy中的networkResponse和cacheResponse为空,说明Cache-Conrol是only-if-cache,则使用缓存
2)如果networkResponse为空,则说明缓存有效,则直接返回cacheResponse
3)如果缓存无效或者需要验证,则调用下一个拦截器直接从网络获取. 在从网络得到响应后,会有两种情况需要处理
- 200 ok 代表着从网络获取到新的响应 (要么是缓存过期获取新内容,要么是缓存不存在从网络获取)
- 304 Not Modify 代表 缓存过期,然后请求网络进行验证,但是内容为改变,这时用新的响应头(Date Expires Cache-Control等)更新旧的缓存响应头,然后将响应返回
至此,缓存拦截器分析完
对于缓存拦截器里面很多的if判断, 这都是根据Http缓存机制来实现的.如果想要清晰的了解缓存拦截器,务必先看Http缓存机制
推荐的读物:
英文比较好的话: RFC2616
<<Http权威指南>>第七章
快速了解的话可以参考tp缓存的介绍