接上次的getResponseWithInterceptorChain()说
开局又是一张图 。。这是OkHttp内部提供的拦截器,实现网络监听、请求以及响应重写、请求失败重试等功能。
上面图里就是okhttp内部给我们提供的拦截器(责任链模式调用下面有介绍),当我们发起一个网络请求的时候Okhttp就会根据这个拦截器链来执行网络操作 上面说了是接getResponseWithInterceptorChain(同步异步最终都会执行的方法)来说 我们就看下这个里面到底执行了什么
//这个名字起的是真6 通过拦截器连获取响应(response)
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, this, eventListener, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());
return chain.proceed(originalRequest);
}
ok 可以看到上面
- 是创建了一个拦截器的集合包括用户添加的拦截器和默认提供拦截器 也就是上面图中那5个拦截器
- 新建拦截器链new RealInterceptorChain()此时传递的index 是0 获取第一个拦截器
- 拦截器链 chain 调用proceed方法 chain.proceed();
看一下proceed方法里面做了什么操作 下图主要代码
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
···
// Call the next interceptor in the chain.
//调用链中的下一个拦截器 index +1 。
RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
writeTimeout);
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);
···
return response;
}
可以看到方法内部又创建了一个RealInterceptorChain,这时创建的是下一个拦截器链,
并调用当前的拦截器的intercept(next)方法将下一个拦截器(index+1)的拦截器传递进去
得到Response对象 下面我们具体分析intercept方法执行了什么
RetryAndFollowUpInterceptor
主要进行网络请求重试和重定向 然而并不是所有的网络请求都重试,它是有一定的限制范围的,OkHttp内部会帮我们检测网络异常和响应码的判断,如果都在它的限制范围内的话,才进行网络重连。
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
···
//1 创建StreamAllocation对象
//分配流 用于网络连接操作
//获取连接服务端的connection和用于与服务端进行数据传输的输入输出流 。
StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
createAddress(request.url()), call, eventListener, callStackTrace);
···
Response priorResponse = null;
while (true) {
//判断是否取消 取消抛异常
if (canceled) {
streamAllocation.release(true);
throw new IOException("Canceled");
}
···
Response response;
boolean releaseConnection = true;
try {
//2 调用proceed方法 方法内又创建一个RealInterceptorChain(index+1) 调用 intercep方法
//执行下一个拦截器链
response = realChain.proceed(request, streamAllocation, null, null);
releaseConnection = false;
}
Request followUp;
try {
//3 根据返回码判断是否重定向
followUp = followUpRequest(response, streamAllocation.route());
}
// 4 判断是否重试 MAX_FOLLOW_UPS=20
if (++followUpCount > MAX_FOLLOW_UPS) {
streamAllocation.release(true);
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
request = followUp;
priorResponse = response;
}
}
其实主要的代码在于通过创建StreamAllocation用于获取client service 的输入输出流
逻辑看while循环中
RealInterceptorChain调用proceed()方法,proceed()方法里又创建了一个RealInterceptorChain对象(是下一个拦截器链 index + 1),然后通过index获取到当前执行到的拦截器,调用拦截器的intercept()方法,这里intercept()方法中,再次调用了RealInterceptorChain的proceed()方法,形成链式调用也是就责任链(其实挺像递归调用)。
这时候index+1 了下一个拦截器就是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());
}
//调用chain.proceed 执行下一个拦截器
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);
String contentType = networkResponse.header("Content-Type");
responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
}
return responseBuilder.build();
}
主要的操作就是为发起的Request请求添加请求头信息,
调用proceed()方法递归调用下个拦截器,
最后面是针对经过gzip压缩过的Response进行解压处理,这里通过判断是否支持gzip压缩且请求头里面的"Content-Encoding"的value是否是"gzip"来判断是否需要进行gzip解压。
主要作用:将用户构建的request 构建成网络请求用的request 并进行网络请求 将网络返回的response 转换成用户可用的response
这时候index+1 变成了CacheInterceptor
主要操作还是intercept
public Response intercept(Chain chain) throws IOException {
//首先通过判断缓存对象是否为null,如果不为null则根据传入的Chain对象的request获取缓存的Response。
Response cacheCandidate = cache != null
? cache.get(chain.request())
: null;
long now = System.currentTimeMillis();
//创建缓存策略对象CacheStrategy,CacheStrategy内部维护了一个Request和一个Response,该类主要是用于解决到底使用网络还是缓存,亦或是两者皆用:
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.
}
//如果当前没有网络且找不到缓存 则构造一个Response对象并返回,其中状态码为504,并设置了提示的message信息。
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();
}
//如果不使用网络请求,直接返回缓存的Response
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());
}
}
//说明缓存还没过期或服务器资源没修改,此时返回缓存;如果服务器资源修改了,
//则使用网络响应返回的最新数据构造Response,接着将最新的数据缓存并移除无效的缓存。
//本地有缓存
if (cacheResponse != null) {
//服务器返回状态码为HTTP_NOT_MODIFIED(304)
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) {
//htpp 头部有响应体且需要缓存
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;
}
CacheInterceptor主要做的操作:
- 从缓存中获取Reponse对象,赋值给caceResponse,如果找不到缓存则为null;
- CacheStrategy这个策略对象将根据相关规则来决定cacheResponse和Request是否有效,如果无效则分别将cacheResponse和request设置为null;
- 如果request和cacheResponse都为null,即没有网络且没有缓存,直接返回一个状态码为504的空Respone对象;
- 如果resquest为null而cacheResponse不为null,即没有网络且有缓存,则直接返回cacheResponse对象;
- 执行下一个拦截器的intercept()方法进行网络请求,获取response;
- 如果服务器资源没有过期(状态码304)且存在缓存,则返回缓存;
- 如果服务器资源有修改,则将返回的最新数据进行缓存并移除掉无效的缓存,最后返回response对象给上一个拦截器
感谢这个文章
后续的是ConnectInterceptor和CallServerInterceptor看下面连接的内容
OkHttp(二)拦截器之ConnectionInterceptor 与CallServerInterceptor