安卓-OkHttp3的责任链模式详解
做Android的人都知道,OkHttp3已经成为了Android开发中最主流的网络请求框架,相信大家第一次用的时候都会被它的简洁所惊艳到。
有人总结它的优势如下
(1) 支持http2,对一台机器的所有请求共享同一个socket
(2) 内置连接池,支持连接复用,减少延迟
(3) 支持透明的gzip压缩响应体
(4) 通过缓存避免重复的请求
(5) 请求失败时自动重试主机的其他ip,自动重定向
(6) 好用的API
那这些都是怎么做到的呢?先抛开1、2、6不谈,其中3、4、5则是通过他的责任链模式实现的,初看起来感觉平平无奇,但是仔细阅读一下源码,发现实在是太优雅了。
下面这张流程图是对OkHttp整个框架的一个较为清晰的描述
1、OkHttp的责任链模式
1.1 什么是责任链模式
百度百科上这样介绍责任链模式
责任链模式是一种设计模式。在责任链模式里,很多对象由每一个对象对其下家的引用而连接起来形成一条链。请求在这个链上传递,直到链上的某一个对象决定处理此请求。发出这个请求的客户端并不知道链上的哪一个对象最终处理这个请求,这使得系统可以在不影响客户端的情况下动态地重新组织和分配责任。
看到定义大家可能都有了感性的认识,其实我们每个人都使用过责任链模式,Java中的异常处理就是一种典型的责任链模式。
1.2 OkHttp的网络请求示例
在OkHttp中,支持两类网络请求,一类是同步请求,另一类是异步请求。不过要注意的是,异步请求回调函数不能更新UI,因为它还是在子线程里面
//同步请求
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder().url("http://www.baidu.com").build();
try {
Response response=client.newCall(request).execute();//直接执行
return response.body().string();
} catch (IOException e) {
return "";
}
//异步请求,通过enqueue放给dispatcher去执行,底层是线程池
OkHttpClient client =new OkHttpClient();
Request request=new Request.Builder().url("http://www.baidu.com").build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
1.3 OkHttp的责任链分类及作用
无论是同步请求还是异步请求,都会去执行RealCall中的execute()函数:
@Override public Response execute() throws IOException {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
transmitter.timeoutEnter();
transmitter.callStart();
try {
client.dispatcher().executed(this);
return getResponseWithInterceptorChain();//使用责任链获取结果
} finally {
client.dispatcher().finished(this);
}
}
//通过责任链获取结果
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(client.interceptors());
interceptors.add(new RetryAndFollowUpInterceptor(client));//重定向责任链
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, transmitter, null, 0,
originalRequest, this, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());
boolean calledNoMoreExchanges = false;
try {
Response response = chain.proceed(originalRequest);//开始责任链的拦截
if (transmitter.isCanceled()) {
closeQuietly(response);
throw new IOException("Canceled");
}
return response;
} catch (IOException e) {
calledNoMoreExchanges = true;
throw transmitter.noMoreExchanges(e);
} finally {
if (!calledNoMoreExchanges) {
transmitter.noMoreExchanges(null);
}
}
}
在这里面我们看到OkHttp的几种拦截器:
- RetryAndFollowUpInterceptor (重试和重定向拦截器)
- 管理连接的重定向
- 网络请求失败重连
- BridgeInterceptor (桥接拦截器)
- 添加请求的header头
- 管理cookie
- 添加gzip的请求头,并且负责对结果解压,这就是最开始提到的为什么其更省网络流量的原因。
- CacheInterceptor(缓存拦截器)
- 对无网环境、有网环境下对缓存做处理
- ConnectInterceptor(连接拦截器)
- 主要工作是获取一条可用的socket连接
- CallServerInterceptor(网络请求拦截器)
- 真的执行网络请求的地方,返回请求的结果
2、OkHttp责任链代码解读
在上一节,我们知道了OkHttp的五大拦截器,在本节给出注释,方便大家理解
2.1 RetryAndFollowUpInterceptor(重试和重定向拦截器)
/**
* RetryAndFollowUpInterceptor
* //重定向拦截器。
*/
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Transmitter transmitter = realChain.transmitter();
int followUpCount = 0;
Response priorResponse = null;
while (true) {
transmitter.prepareToConnect(request);//准备socket连接
if (transmitter.isCanceled()) {
throw new IOException("Canceled");
}
Response response;
boolean success = false;
try {//上来就交给下一个拦截链,因为需要得到重定向的信息(301之类的)
response = realChain.proceed(request, transmitter, null);
success = true;
} catch (RouteException e) {
// The attempt to connect via a route failed. The request will not have been sent.
if (!recover(e.getLastConnectException(), transmitter, false, request)) {
throw e.getFirstConnectException();
}
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, transmitter, requestSendStarted, request)) throw e;
continue;
} finally {
// The network call threw an exception. Release any resources.
if (!success) {
transmitter.exchangeDoneDueToException();
}
}
// 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();
}
Exchange exchange = Internal.instance.exchange(response);
Route route = exchange != null ? exchange.connection().route() : null;
Request followUp = followUpRequest(response, route);
if (followUp == null) {
if (exchange != null && exchange.isDuplex()) {
transmitter.timeoutEarlyExit();
}
return response;
}
RequestBody followUpBody = followUp.body();
if (followUpBody != null && followUpBody.isOneShot()) {
return response;
}
closeQuietly(response.body());
if (transmitter.hasExchange()) {
exchange.detachWithViolence();
}
if (++followUpCount > MAX_FOLLOW_UPS) {
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
request = followUp;
priorResponse = response;
}
}
2.2 BridgeInterceptor(桥接连接器)
/**
* BridgeInterceptor
*桥接拦截器。负责将原始Requset转换给发送给服务端的Request以及将Response转化成对调用方友好的Response,
*具体就是对request添加Content-Type、Content-Length、Connection、Accept-Encoding等请求头以及对返回结果进行解压等。
*导致OkHttp更省空间的gzip请求头的添加和请求内容的解压就是在这里做的
*/
@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");//添加GZIP请求头,减少响应的体积
}
List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());//Cookie的管理
if (!cookies.isEmpty()) {
requestBuilder.header("Cookie", cookieHeader(cookies));//自动加cookie
}
if (userRequest.header("User-Agent") == null) {//UA
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);
//解压GZIP
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();//返回响应
}
2.3 CacheInterceptor(缓存拦截器)
//CacheInterceptor
//缓存拦截器
@Override public Response intercept(Chain chain) throws IOException {
Response cacheCandidate = cache != null
? cache.get(chain.request())//获取request对应缓存的response.如果用户没有配置缓存拦截器
: null;//那么cacheCandidate为null。cacheCandidate是候选缓存的意思
long now = System.currentTimeMillis();//执行缓存策略
CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
Request networkRequest = strategy.networkRequest;//如果为null,那么说明不使用网络
Response cacheResponse = strategy.cacheResponse;//获取候选缓存中的response
if (cache != null) {
cache.trackResponse(strategy);
}
//假如候选缓存不为空,但是response为空,说明缓存无效,要关闭资源
if (cacheCandidate != null && cacheResponse == null) {
closeQuietly(cacheCandidate.body()); //
}
//如果被禁止使用网络,并且缓存无效,我们返回失败
if (networkRequest == null && cacheResponse == null) {
return new Response.Builder()
.request(chain.request())
.protocol(Protocol.HTTP_1_1)
.code(504)//504错误
.message("Unsatisfiable Request (only-if-cached)")
.body(Util.EMPTY_RESPONSE)
.sentRequestAtMillis(-1L)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
}
//如果我们不要网络,但是缓存有效,我们直接返回存在的缓存
if (networkRequest == null) {
return cacheResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.build();
}
/**********
* 下面是需要请求网络的部分
* **********/
Response networkResponse = null;
/**
* 执行下一个拦截链,取出网络请求结果,在这里来说就是连接拦截器,返回状态码的
*/
try {
networkResponse = chain.proceed(networkRequest);
} finally {
//如果请求失败了,关闭资源
if (networkResponse == null && cacheCandidate != null) {
closeQuietly(cacheCandidate.body());
}
}
//如果从本地拿出的缓存不为空
if (cacheResponse != null) {//先看一下状态码是不是304,304就是内容为改变 not modified的状态
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();
//更新一下本地的缓存,然后返回响应
cache.trackConditionalCacheHit();
cache.update(cacheResponse, response);
return response;
} else {
closeQuietly(cacheResponse.body());
}
}
//如果连接拦截器没有拦截住,那么返回的状态码就不是304了,而是200之类的,这时候response里就有
//请求的网络信息,然后在这里构建response
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;
}
2.4 ConnectInterceptor(连接拦截器)
/**
* ConnectInterceptor
* 连接拦截器。寻找一个可用的socket连接
*/
@Override public Response intercept(Chain chain) throws IOException {
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Request request = realChain.request();
Transmitter transmitter = realChain.transmitter();
// We need the network to satisfy this request. Possibly for validating a conditional GET.
boolean doExtensiveHealthChecks = !request.method().equals("GET");
Exchange exchange = transmitter.newExchange(chain, doExtensiveHealthChecks);
//寻找一个可用链接,然后执行下一个拦截器,也就是网络请求拦截器
return realChain.proceed(request, transmitter, exchange);
}
2.5 CallServerInterceptor(网络请求拦截器)
/**
* CallServerInterceptor
* 网络请求拦截器。作用是通过socket拿回来网络请求结果
*/
@Override public Response intercept(Chain chain) throws IOException {
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Exchange exchange = realChain.exchange();
Request request = realChain.request();
long sentRequestMillis = System.currentTimeMillis();
exchange.writeRequestHeaders(request);
boolean responseHeadersStarted = false;
Response.Builder responseBuilder = null;
if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
//检查一下状态码
if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
exchange.flushRequest();
responseHeadersStarted = true;
exchange.responseHeadersStart();
responseBuilder = exchange.readResponseHeaders(true);
}
//构建响应体
if (responseBuilder == null) {
if (request.body().isDuplex()) {
// Prepare a duplex body so that the application can send a request body later.
exchange.flushRequest();
BufferedSink bufferedRequestBody = Okio.buffer(
exchange.createRequestBody(request, true));
request.body().writeTo(bufferedRequestBody);
} else {
// Write the request body if the "Expect: 100-continue" expectation was met.
BufferedSink bufferedRequestBody = Okio.buffer(
exchange.createRequestBody(request, false));
request.body().writeTo(bufferedRequestBody);
bufferedRequestBody.close();
}
} else {
exchange.noRequestBody();
if (!exchange.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.
exchange.noNewExchangesOnConnection();
}
}
} else {
exchange.noRequestBody();
}
if (request.body() == null || !request.body().isDuplex()) {
exchange.finishRequest();
}
if (!responseHeadersStarted) {
exchange.responseHeadersStart();
}
if (responseBuilder == null) {
responseBuilder = exchange.readResponseHeaders(false);
}
Response response = responseBuilder
.request(request)
.handshake(exchange.connection().handshake())
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
int code = response.code();
if (code == 100) {
// server sent a 100-continue even though we did not request one.
// try again to read the actual response
response = exchange.readResponseHeaders(false)
.request(request)
.handshake(exchange.connection().handshake())
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
code = response.code();
}
exchange.responseHeadersEnd(response);
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(exchange.openResponseBody(response))
.build();
}
if ("close".equalsIgnoreCase(response.request().header("Connection"))
|| "close".equalsIgnoreCase(response.header("Connection"))) {
exchange.noNewExchangesOnConnection();
}
if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
throw new ProtocolException(
"HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
}
return response;
}