【安卓开发系列 -- APP 开源框架】网络请求框架 OKHTTP -- 拦截器
【1】OKHTTP 拦截器概述
【1.1】拦截器中的请求(Request)与响应(Response)类分析
public final class Request {
// 请求地址
final HttpUrl url;
// 请求方法
final String method;
// 请求头
final Headers headers;
// 请求体
final @Nullable RequestBody body;
// 请求标记
final Object tag;
// 带有来自服务器或客户机的缓存指令的缓存控制头
private volatile CacheControl cacheControl;
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;
}
...
}
public final class Response implements Closeable {
// 请求消息
final Request request;
// 请求协议
final Protocol protocol;
// 响应码
final int code;
// 响应信息
final String message;
// TLS握手的记录
final @Nullable Handshake handshake;
// 响应头,包含返回的消息类型(content-type)、返回消息的长度content-length
final Headers headers;
// 响应体(服务器端返回的消息内容)
final @Nullable ResponseBody body;
// 网络请求的响应Response
final @Nullable Response networkResponse;
// 缓存的响应Response
final @Nullable Response cacheResponse;
// 先前的响应
final @Nullable Response priorResponse;
// 发送请求的时间(毫秒单位)
final long sentRequestAtMillis;
// 接收到响应的时间(毫秒单位)
final long receivedResponseAtMillis;
// 缓存控制实例
private volatile CacheControl cacheControl; // Lazily initialized.
Response(Builder builder) {
this.request = builder.request;
this.protocol = builder.protocol;
this.code = builder.code;
this.message = builder.message;
this.handshake = builder.handshake;
this.headers = builder.headers.build();
this.body = builder.body;
this.networkResponse = builder.networkResponse;
this.cacheResponse = builder.cacheResponse;
this.priorResponse = builder.priorResponse;
this.sentRequestAtMillis = builder.sentRequestAtMillis;
this.receivedResponseAtMillis = builder.receivedResponseAtMillis;
}
...
}
【1.2】Interceptor接口
public interface Interceptor {
// 拦截方法,拦截器插入拦截逻辑的主要方法
Response intercept(Chain chain) throws IOException;
// 责任链中的节点接口
interface Chain {
// 用于获取HTTP请求
Request request();
// 用于责任链中的任务的传递
Response proceed(Request request) throws IOException;
/**
* 返回请求将在其上执行的连接;
* 这只适用于网络拦截器的chains,对于应用程序拦截器总是空的;
*/
@Nullable Connection connection();
// 返回请求Call实例
Call call();
// 返回链接超时时长
int connectTimeoutMillis();
// 创建具有链接超时的责任链节点
Chain withConnectTimeout(int timeout, TimeUnit unit);
// 返回读超时时长
int readTimeoutMillis();
// 创建具有读超时的责任链节点
Chain withReadTimeout(int timeout, TimeUnit unit);
// 返回写超时时长
int writeTimeoutMillis();
// 创建具有写超时的责任链节点
Chain withWriteTimeout(int timeout, TimeUnit unit);
}
}
【2】OKHTTP内置拦截器
【2.1】RetryAndFollowUpInterceptor,负责失败重试以及重定向;
重定向相关的HTTP状态码
重定向VS请求转发
区别
重定向时,客户端发起两次请求;请求转发时,客户端只发起一次请求;
重定向后,浏览器地址栏url变成第二个url;请求转发没有变(请求转发对于客户端是透明的);
流程
重定向,用户请求----->服务器入口------->组件------>服务器出口------->用户----(重定向)--->新的请求;
请求转发,用户请求----->服务器入口------->组件1---(转发)---->组件2------->服务器出口------->用户;
RetryAndFollowUpInterceptor -- intercept 方法
public final class RetryAndFollowUpInterceptor implements Interceptor {
...
@Override public Response intercept(Chain chain) throws IOException {
// 获取HTTP请求
Request request = chain.request();
// 责任链节点类型转换为RealInterceptorChain
RealInterceptorChain realChain = (RealInterceptorChain) chain;
// 获取责任链节点对应的请求Call
Call call = realChain.call();
// 获取责任链节点对应的事件监听器
EventListener eventListener = realChain.eventListener();
// 新建StreamAllocation并赋值给当前拦截器的streamAllocation属性
// StreamAllocation相当于是个管理类,其管理了Connections、Streams和Calls,
// 该类初始化一个Socket连接对象以便获取输入/输出流对象
StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
createAddress(request.url()), call, eventListener, callStackTrace);
this.streamAllocation = streamAllocation;
// 记录重定向的次数
int followUpCount = 0;
// 先前Response实例
Response priorResponse = null;
while (true) {
if (canceled) {
// 删除连接上的call请求
streamAllocation.release();
throw new IOException("Canceled");
}
Response response;
boolean releaseConnection = true;
try {
// 继续执行下一个Interceptor
// 网络请求
response = realChain.proceed(request, streamAllocation, null, null);
// 表示是否要释放连接,在 finally 中会使用到
releaseConnection = false;
} catch (RouteException e) {
// The attempt to connect via a route failed. The request will not have been sent.
// 处理RouteException
// 通过一个路由的连接尝试失败,该请求没有被发送
// 检测路由异常是否能重新连接
if (!recover(e.getLastConnectException(), streamAllocation, false, request)) {
// 不可以重连则直接抛出异常
throw e.getLastConnectException();
}
// 可以重新连接,那么就不要释放连接
releaseConnection = false;
// 重新进行while循环,进行网络请求
continue;
} catch (IOException e) {
// An attempt to communicate with a server failed. The request may have been sent.
// 处理IOException
// 尝试与服务器通信失败,该请求已经被发送
boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
// 检查IOException是否可以重连
// 不可以重连则直接抛出异常
if (!recover(e, streamAllocation, requestSendStarted, request)) throw e;
// 可以重新连接,那么就不要释放连接
releaseConnection = false;
// 重新进行while循环,进行网络请求
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不为空时则进行重定向处理
// 当代码可以执行到followUpRequest方法就表示该请求是成功的,但是服务器返回的状态码可能不是200 ok的情况,
// 此时还需要对该请求进行检测,其主要就是通过返回码进行判断的
Request followUp = followUpRequest(response, streamAllocation.route());
if (followUp == null) {
if (!forWebSocket) {
streamAllocation.release();
}
return response;
}
closeQuietly(response.body());
// 重定向的次数不能超过20次
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);
this.streamAllocation = streamAllocation;
} 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;
}
}
...
}
RetryAndFollowUpInterceptor -- 网络请求异常重连检查
// 网络请求异常重连机制检查
public final class RetryAndFollowUpInterceptor implements Interceptor {
...
private boolean recover(IOException e, StreamAllocation streamAllocation,
boolean requestSendStarted, Request userRequest) {
streamAllocation.streamFailed(e);
// The application layer has forbidden retries.
// 判断OkHttpClient是否支持失败重连的机制
if (!client.retryOnConnectionFailure()) return false;
// We can't send the request body again.
// 在该方法中传入的routeException值是否为true
if (requestSendStarted && userRequest.body() instanceof UnrepeatableRequestBody) return false;
// This exception is fatal.
// isRecoverable检测该异常是否是致命的
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;
}
private boolean isRecoverable(IOException e, boolean requestSendStarted) {
// If there was a protocol problem, don't recover.
// ProtocolException这种异常属于严重异常,不能进行重新连接
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.
// 若异常是X509TrustManager的证书异常则无须再尝试
if (e.getCause() instanceof CertificateException) {
return false;
}
}
// 验证异常
if (e instanceof SSLPeerUnverifiedException) {
// e.g. a certificate pinning error.
return false;
}
return true;
}
...
}
【2.2】BridgeInterceptor,负责把用户构造的请求转换为发送给服务器的请求,把服务器返回的响应转换为对用户友好的响应;
public final class BridgeInterceptor implements Interceptor {
...
@Override public Response intercept(Chain chain) throws IOException {
// 获取HTTP请求
Request userRequest = chain.request();
// 新建HTTP请求构造器
Request.Builder requestBuilder = userRequest.newBuilder();
// 获取请求体
RequestBody body = userRequest.body();
// 对请求头的补充
if (body != null) {
// 进行Header的包装
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");
}
}
// 添加请求头的Host参数
if (userRequest.header("Host") == null) {
requestBuilder.header("Host", hostHeader(userRequest.url(), false));
}
// 添加请求头的Connection参数
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.
// 设置Accept-Encoding参数
boolean transparentGzip = false;
if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
transparentGzip = true;
requestBuilder.header("Accept-Encoding", "gzip");
}
// cookie头的添加
// 从OkhttpClient配置的cookieJar获取cookie
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());
// ------------------------------------------------------------------------------------
// 以下是处理服务器的响应
// 解析服务器返回的Header,如果没有这个cookie,则不进行解析
HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
// 构建响应构建器
Response.Builder responseBuilder = networkResponse.newBuilder()
.request(userRequest);
// 判断服务器是否支持gzip压缩,如果支持,则将压缩提交给Okio库来处理
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,负责读取缓存以及更新缓存;
public final class CacheInterceptor implements Interceptor {
...
@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;
// 追溯满足缓存策略的HTTP响应
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.
// 根据策略,不使用网络,又没有缓存的直接报错,并返回错误码504
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 {
// 前面两个都没有返回,继续执行下一个Interceptor
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.
// 接收到网络结果,如果响应code是304,则使用缓存,返回缓存结果
/**
* 304 Not Modified,未修改,所请求的资源未修改,服务器返回此状态码时,不会返回任何资源;
*/
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 {
// 从缓存中移除HTTP请求
cache.remove(networkRequest);
} catch (IOException ignored) {
// The cache cannot be written.
}
}
}
return response;
}
...
}
【2.4】ConnectInterceptor,负责与服务器建立连接;
public final class ConnectInterceptor implements Interceptor {
...
@Override public Response intercept(Chain chain) throws IOException {
// 获取责任链节点
RealInterceptorChain realChain = (RealInterceptorChain) chain;
// 获取责任链节点的HTTP响应
Request request = realChain.request();
// 获取责任链节点的StreamAllocation实例
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, chain, doExtensiveHealthChecks);
// 建立连接
RealConnection connection = streamAllocation.connection();
// 责任链中的任务向下传递
return realChain.proceed(request, streamAllocation, httpCodec, connection);
}
}
【2.5】CallServerInterceptor,负责从服务器读取响应的数据;
public final class CallServerInterceptor implements Interceptor {
...
@Override public Response intercept(Chain chain) throws IOException {
// 获取责任链节点
RealInterceptorChain realChain = (RealInterceptorChain) chain;
// 获取责任链节点输出流
HttpCodec httpCodec = realChain.httpStream();
// 获取责任链节点的StreamAllocation实例
StreamAllocation streamAllocation = realChain.streamAllocation();
// 获取责任链节点的连接
RealConnection connection = (RealConnection) realChain.connection();
// 获取责任链节点的HTTP响应
Request request = realChain.request();
// 发送请求的时间戳
long sentRequestMillis = System.currentTimeMillis();
// 写入请求头
realChain.eventListener().requestHeadersStart(realChain.call());
httpCodec.writeRequestHeaders(request);
realChain.eventListener().requestHeadersEnd(realChain.call(), 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.
//
// 如果请求中存在“Expect:100-continue”标头,请在发送请求主体之前等待“HTTP / 1.1 100 Continue”响应;
// 如果没有得到响应,则返回得到的内容(例如4xx响应)而不发送请求主体;
if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
httpCodec.flushRequest();
realChain.eventListener().responseHeadersStart(realChain.call());
responseBuilder = httpCodec.readResponseHeaders(true);
}
// 写入请求体
if (responseBuilder == null) {
// Write the request body if the "Expect: 100-continue" expectation was met.
// 如果满足了“Expect:100 continue”的期望则写入请求正文
realChain.eventListener().requestBodyStart(realChain.call());
long contentLength = request.body().contentLength();
CountingSink requestBodyOut =
new CountingSink(httpCodec.createRequestBody(request, contentLength));
BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
request.body().writeTo(bufferedRequestBody);
bufferedRequestBody.close();
realChain.eventListener()
.requestBodyEnd(realChain.call(), requestBodyOut.successfulCount);
} 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.
//
// 若不满足"Expect: 100-continue"则禁止复用HTTP/1连接
// 否则仍然有义务传输请求主体以便使连接保持一致状态
streamAllocation.noNewStreams();
}
}
// 结束请求
httpCodec.finishRequest();
// 读取响应头信息
if (responseBuilder == null) {
realChain.eventListener().responseHeadersStart(realChain.call());
responseBuilder = httpCodec.readResponseHeaders(false);
}
// 构造响应实例
Response response = responseBuilder
.request(request)
.handshake(streamAllocation.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
// 处理状态码100
// 100-continue,继续,客户端应继续其请求
responseBuilder = httpCodec.readResponseHeaders(false);
response = responseBuilder
.request(request)
.handshake(streamAllocation.connection().handshake())
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
code = response.code();
}
realChain.eventListener()
.responseHeadersEnd(realChain.call(), response);
// 响应码101,Switching Protocols,切换协议;
// 服务器根据客户端的请求切换协议,只能切换到更高级的协议,例如切换到HTTP的新版本协议
if (forWebSocket && code == 101) {
// Connection is upgrading, but we need to ensure interceptors see a non-null response body.
// 处理WebSocket的协议升级
// 连接正在升级,但需要确保拦截器看到非空响应主体
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();
}
// 响应码204/205
// 响应码204,No Content,无内容;服务器成功处理,但未返回内容;在未更新网页的情况下,可确保浏览器继续显示当前文档
// 响应码205,Reset Content,重置内容;服务器处理成功,用户终端应重置文档视图,可通过此返回码清除浏览器的表单域
if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
throw new ProtocolException(
"HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
}
return response;
}
...
}
参考致谢
本博客为博主的学习实践总结,并参考了众多博主的博文,在此表示感谢,博主若有不足之处,请批评指正。
【1】OkHttp3.0(二)-OkHttpClient类、Request类、Call类、Response的简单分析
【2】HTTP状态码
【4】OkHttp 3.7源码分析(二)——拦截器&一个实际网络请求的实现
【5】okhttp之旅(三)--拦截器Interceptor概述
【6】okhttp之旅(四)--RetryAndFollowUpInterceptor重定向拦截器
【7】OKHTTP拦截器RetryAndFollowUpInterceptor的简单分析
【8】okhttp之旅(五)--BridgeInterceptor桥拦截器
【9】OKHTTP拦截器BridgeInterceptor的简单分析
【10】okhttp之旅(六)--CacheInterceptor缓存拦截器
【11】OKHTTP拦截器缓存策略CacheInterceptor的简单分析
【12】okhttp之旅(七)--ConnectInterceptor连接拦截器
【13】OKHTTP拦截器ConnectInterceptor的简单分析