本篇文章我们将介绍 OkHttp 的拦截器,拦截器是 OkHttp 的核心,正是因为 OkHttp 内置的五大拦截器各司其职,才使得使用者可以轻松的发送网络请求并收到响应。这五大拦截器分别是:

  1. 重定向与重试拦截器:负责判断是否需要重新发起整个请求
  2. 桥接拦截器:补全请求,并对响应进行额外处理
  3. 缓存拦截器:请求前查询缓存,获得响应并判断是否需要缓存
  4. 连接拦截器:与服务器完成 TCP 连接
  5. 请求服务拦截器:与服务器通信,封装请求数据、解析响应数据(如:HTTP报文)

这些拦截器是通过责任链串联起来的。所以我们先来看看 OkHttp 是如何应用责任链的。

一、OkHttp 的责任链

在上一篇讲分发器时我们能看到,RealCall 不论是被同步执行,还是被异步执行,都调用到了一个使用责任链的方法 getResponseWithInterceptorChain(),该方法会将所有的拦截器都添加到 interceptors 这个列表中:

 Response getResponseWithInterceptorChain() throws IOException {// Build a full stack of interceptors.List<Interceptor> interceptors = new ArrayList<>();欧插// 添加保存在 OkHttpClient 中的自定义拦截器interceptors.addAll(client.interceptors());// 添加一系列 OkHttp 内置的拦截器interceptors.add(retryAndFollowUpInterceptor);interceptors.add(new BridgeInterceptor(client.cookieJar()));interceptors.add(new CacheInterceptor(client.internalCache()));interceptors.add(new ConnectInterceptor(client));if (!forWebSocket) {// 添加在 OkHttpClient 中自定义的网络拦截器interceptors.addAll(client.networkInterceptors());}// 添加 OkHttp 内置的请求服务拦截器interceptors.add(new CallServerInterceptor(forWebSocket));// 创建一个责任链对象,传了 interceptors 和 originalRequest,后者表示原始请求Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,originalRequest, this, eventListener, client.connectTimeoutMillis(),client.readTimeoutMillis(), client.writeTimeoutMillis());// 执行责任链,获得响应体并返回return chain.proceed(originalRequest);}

我们先不考虑 OkHttpClient 中自定义的拦截器,在内置的五大拦截器被添加到 interceptors 后,创建了一个 RealInterceptorChain 对象,并调用 RealInterceptorChain 的 proceed():

 // 责任链上的第几个拦截器private final int index;// 当前拦截器被调用的次数private int calls;public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,RealConnection connection) throws IOException {if (index >= interceptors.size()) throw new AssertionError();// 调用次数+1calls++;...// Call the next interceptor in the chain.// 在 getResponseWithInterceptorChain() 创建 RealInterceptorChain 时,index 传的是 0RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,writeTimeout);// 由于 index 是 0,所以取出的是第一个拦截器 RetryAndFollowUpInterceptorInterceptor interceptor = interceptors.get(index);// 调用下一个拦截器,并将新产生的 RealInterceptorChain 对象传进去Response response = interceptor.intercept(next);...return response;}

来到 RetryAndFollowUpInterceptor 的 intercept(),我们先只看责任链流程:

 @Overridepublic Response intercept(Chain chain) throws IOException {// 没对 Request 进行处理Request request = chain.request();RealInterceptorChain realChain = (RealInterceptorChain) chain;Call call = realChain.call();Response priorResponse = null;while (true) {...Response response;try {// 执行责任链,得到 Responseresponse = realChain.proceed(request, streamAllocation, null, null);} catch (RouteException e) {...} finally {...}// 对 Response 做处理if (priorResponse != null) {response = response.newBuilder().priorResponse(priorResponse.newBuilder().body(null).build()).build();}Request followUp = followUpRequest(response, streamAllocation.route());// 如果不做重定向就返回 responseif (followUp == null) {if (!forWebSocket) {streamAllocation.release();}return response;}...}}

我们就先看个大概,拦截器在做事的时候一般会有如下几步:

  1. 从参数的责任链对象中取出 Request,并根据自身功能需求对 Request 做出修改。修改 Request 并不是所有拦截器一定会做的,像上面的 RetryAndFollowUpInterceptor 由于自身并没有修改 Request 的需求,所以它就没改
  2. 调用 RealInterceptorChain 的 proceed() 让责任链向下执行,在 proceed() 内会取出 interceptors 集合中的下一个拦截器,并调用该拦截器的 intercept(),这样就会回到第 1 步,这是个递归过程
  3. 递归到最后一个拦截器执行完 intercept() 得到 Response,在将 Response 返回给上一层调用者之前,会根据自身需要,对 Response 的内容做出修改,这个修改同样也不是每个拦截器必须要做的

以上是 OkHttp 责任链的执行流程,那么从整体结构上来看,责任链的结构如下:


下面就来看一下内置的五大拦截器,注意后面叙述的时候我们会默认没有向 interceptors 集合中添加自定义的拦截器,interceptors 中只有五个内置拦截器。

二、重试与重定向拦截器

RetryAndFollowUpInterceptor,是整个责任链中的第一个,这意味着它会是首个接触到 Request 与最后接收到 Response 的拦截器,本拦截器的主要功能就是判断是否需要重试与重定向,这两个功能在 intercept() 内的 while 循环中完成:

 @Overridepublic Response intercept(Interceptor.Chain chain) throws IOException {// 从责任链上拿到 Request,没有对其进行修改Request request = chain.request();RealInterceptorChain realChain = (RealInterceptorChain) chain;Call call = realChain.call();EventListener eventListener = realChain.eventListener();StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),createAddress(request.url()), call, eventListener, callStackTrace);this.streamAllocation = streamAllocation;// 重定向次数int followUpCount = 0;// 重定向时会用到,用来记录上一次响应Response priorResponse = null;while (true) {if (canceled) {streamAllocation.release();throw new IOException("Canceled");}Response response;boolean releaseConnection = true;// 1.重试try {// 把请求交给责任链上的下一个拦截器,注意如果在 proceed() 内发生了异常,// 那么 releaseConnection 就还是初始值 trueresponse = realChain.proceed(request, streamAllocation, null, null);releaseConnection = false;} catch (RouteException e) {// 路由异常,连接未成功,请求还没有发出去,用 recover() 来判断是否进行重试if (!recover(e.getLastConnectException(), streamAllocation, false, request)) {throw e.getLastConnectException();}releaseConnection = false;// 走到这里说明 recover() 返回 true,表示可以重试,那么 if 未命中不会抛出异常,// continue 执行下一次 while 循环,重新执行整个责任链continue;} catch (IOException e) {// 请求已发出,但是和服务器通信失败了,比如 Socket 读写数据时连接断开// Http2 才会抛出 ConnectionShutdownException,所以对于 Http1 来说,requestSendStarted 一定是 trueboolean requestSendStarted = !(e instanceof ConnectionShutdownException);if (!recover(e, streamAllocation, requestSendStarted, request)) throw e;releaseConnection = false;continue;} finally {// 如果不是以上两种异常,不能进行重试,就释放所有资源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();}// 2.重定向。如果不需要做重定向,那么 followUp 就是 nullRequest followUp = followUpRequest(response, streamAllocation.route());// 不需要重定向,直接将 response 返回if (followUp == null) {if (!forWebSocket) {streamAllocation.release();}return response;}// 能执行到这说明上面没返回,那就是需要做重定向了closeQuietly(response.body());// 重定向次数不能超过 MAX_FOLLOW_UPS(默认为 20),20 是参考了其它浏览器的设置,// 如 Chrome 21 次,Firefox 20 次,Safari 16 次,Http1.0 推荐 5 次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,而本次得到的 response 将是下一次循环中的 priorResponserequest = followUp;priorResponse = response;}}

2.1 重试

重试逻辑其实就是在 while 循环的 try-catch-finally 代码块中。只有在发生了 RouteException 和 IOException 时,才有可能进行重试,决定是否要进行重试的是 recover():

 private boolean recover(IOException e, StreamAllocation streamAllocation,boolean requestSendStarted, Request userRequest) {streamAllocation.streamFailed(e);// OkHttpClient 客户端配置了不允许重试if (!client.retryOnConnectionFailure()) return false;// Request 自己配置了不允许重试if (requestSendStarted && userRequest.body() instanceof UnrepeatableRequestBody)return false;// 致命异常不允许重试if (!isRecoverable(e, requestSendStarted)) return false;// 没有更多路线不允许重试if (!streamAllocation.hasMoreRoutes()) return false;return true;}

recover() 内用 4 个 if 条件判断是否能进行重试,只要满足重试条件,会在 intercept() 的 while 无限循环中一直帮我们重试,下面来看这 4 个条件的具体内容:

客户端是否允许重试

retryOnConnectionFailure() 获取的是 OkHttpClient 的 retryOnConnectionFailure 属性:

 public boolean retryOnConnectionFailure() {return retryOnConnectionFailure;}

该属性会决定由当前 OkHttpClient 发出的所有 Request 是否允许进行重试,可以通过 OkHttpClient.Builder 的 retryOnConnectionFailure() 对该属性进行设置,默认值为 true,表示允许客户端进行重试。

单个 Request 是否允许重试

配置某一个 Request 是否进行重试,取决于 requestSendStarted 的值以及 RequestBody 是否是 UnrepeatableRequestBody 接口的实现类。

回看 intercept() 内抛出 RouteException 和 IOException 的两个 catch 代码块:

 @Overridepublic Response intercept(Interceptor.Chain chain) throws IOException {...while (true) {...try {response = realChain.proceed(request, streamAllocation, null, null);releaseConnection = false;} catch (RouteException e) {if (!recover(e.getLastConnectException(), streamAllocation, false, request)) {throw e.getLastConnectException();}releaseConnection = false;continue;} catch (IOException e) {// 请求已发出,但是和服务器通信失败了,比如 Socket 读写数据时连接断开// Http2 才会抛出 ConnectionShutdownException,所以对于 Http1 来说,requestSendStarted 一定是 trueboolean requestSendStarted = !(e instanceof ConnectionShutdownException);if (!recover(e, streamAllocation, requestSendStarted, request)) throw e;releaseConnection = false;continue;} ...}...}

发生 RouteException 调用 recover() 时,requestSendStarted 直接传了 false,发生 IOException 时,requestSendStarted 只有在抛出的异常是 ConnectionShutdownException 的实例时才为 false,而由于 Http2 才会抛出 ConnectionShutdownException,所以对于 Http1 来说,requestSendStarted 一定是 true。

至于第二个条件中的 UnrepeatableRequestBody 实际上是一个空接口:

public interface UnrepeatableRequestBody {}

只起到标记作用,如果你并不想让某个 Request 进行重试,可以自定义一个 RequestBody 实现该接口:

 class MyRequestBody extends RequestBody implements UnrepeatableRequestBody {@Nullable@Overridepublic MediaType contentType() {return null;}@Overridepublic void writeTo(BufferedSink sink) throws IOException {}}

然后使用这个 RequestBody 构造 Request:

 Request request = new Request.Builder().url("https://www.xxx.com").post(new MyRequestBody()).build();

这样这个 Request 就不会进行重试。

是否是可重试的异常

某些异常发生时,是不允许重试的,因为这些异常是真的因为客户端或服务端的代码有问题,即便重试无数次得到的也都是错误结果;而有些异常可能是由于网络波动导致异常发生,换个路线重试可能就会解决问题。因此需要 isRecoverable() 判断,哪些异常可以重试,哪些不可以:

 private boolean isRecoverable(IOException e, boolean requestSendStarted) {// 发生协议异常,不会重试if (e instanceof ProtocolException) {return false;}// 一般的 IO 中断异常不会重试,但是如果是 Socket 超时异常,可以尝试其它路线(如果有)if (e instanceof InterruptedIOException) {// 有可能是网络波动造成了 Socket 的连接超时,可以使用不同的路线进行重试return e instanceof SocketTimeoutException && !requestSendStarted;}// SSL 握手异常,如果是证书出现问题,不能重试if (e instanceof SSLHandshakeException) {// 由 X509TrustManager 抛出的 CertificateException,不重试if (e.getCause() instanceof CertificateException) {return false;}}// SSL 未授权异常(证书校验失败,不匹配或过期等问题)不重试if (e instanceof SSLPeerUnverifiedException) {return false;}return true;}

我们主要来解释一下协议异常。ProtocolException 是一种 IOException,比如 OkHttp 的 CallServerInterceptor 在其处理责任链的 intercept() 内就抛出了这种异常:

 @Overridepublic Response intercept(Interceptor.Chain chain) throws IOException {...if ((code == 204 || code == 205) && response.body().contentLength() > 0) {throw new ProtocolException("HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());}...}

看条件,是状态码为 204 或 205 且响应体内容长度大于 0 时会抛出 ProtocolException。两个状态码的含义分别为:

  • 204:No Content,表示无内容。服务器成功处理,但未返回内容。在未更新网页的情况下,可确保浏览器继续显示当前文档
  • 205:Reset Content,表示重置内容。服务器处理成功,用户终端(例如:浏览器)应重置文档视图。可通过此返回码清除浏览器的表单域

也就是说,状态码告诉我们服务器没有返回内容,即没有响应体,但是我们通过代码拿到响应体的内容长度大于 0,这两个条件前后矛盾,有可能是服务器响应本身就存在问题,就算重试也还是得到一个错误结果,于是抛出 ProtocolException 不进行重试。

是否有更多路线

我们在配置 OkHttpClient 的时候可能会为客户端配置多个代理,而服务器端的同一个域名也可能会有多个 ip,当某条路线通信失败后,如果存在更多路线,就会换个路线尝试。比如说,restapi.amap.com 解析为 IP1 和 IP2,如果 IP1 通信失败会重试 IP2。

最后我们用一张图来总结一下发生异常后重试的流程:


可以看出,重试条件还是比较苛刻的。

2.2 重定向

如果不满足重试条件,即在 RouteException 和 IOException 中没能执行到 continue 跳出本次循环的话,程序就会运行到 followUpRequest() 进行重定向的相关操作:

 /*** 如果此方法返回空,表示不需要重定向;如果返回非空,就要对返回的 Request 对象做重新请求。* 需要注意的是,在拦截器中定义的最大重定向次数为 20 次*/private Request followUpRequest(Response userResponse, Route route) throws IOException {// 如果请求失败,连 Response 都不存在就会抛出异常if (userResponse == null) throw new IllegalStateException();int responseCode = userResponse.code();final String method = userResponse.request().method();switch (responseCode) {// 407:客户端使用了 HTTP 代理服务器,在请求头中添加【Proxy-Authorization】,让代理服务器授权case HTTP_PROXY_AUTH:Proxy selectedProxy = route != null? route.proxy(): client.proxy();if (selectedProxy.type() != Proxy.Type.HTTP) {throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");}// 调用 OkHttpClient 代理的鉴权接口return client.proxyAuthenticator().authenticate(route, userResponse);// 401:需要身份验证,有些服务器接口需要验证使用者身份,在请求头中添加【Authorization】case HTTP_UNAUTHORIZED:return client.authenticator().authenticate(route, userResponse);// 308:永久重定向case HTTP_PERM_REDIRECT:// 307:临时重定向case HTTP_TEMP_REDIRECT:// 如果请求方式不是 GET 或 HEAD,则不自动重定向请求if (!method.equals("GET") && !method.equals("HEAD")) {return null;}// 300:多种选择。请求的资源可包括多个位置,相应可返回一个资源特征与地址的列表用于客户端选择case HTTP_MULT_CHOICE:// 301:永久移动。请求的资源已被永久的移动到新 URI,返回信息会包括新的 URI,// 浏览器会自动定向到新 URI。今后任何新的请求都应使用新的 URI 代替case HTTP_MOVED_PERM:// 302:临时移动。与 301 类似。但资源只是临时被移动。客户端应继续使用原有 URIcase HTTP_MOVED_TEMP:// 303:查看其它地址。与 301 类似。使用 GET 和 POST 请求查看case HTTP_SEE_OTHER:// 客户端不允许重定向就返回 nullif (!client.followRedirects()) return null;// 从响应头取出 Location,并配置新请求的 urlString location = userResponse.header("Location");if (location == null) return null;HttpUrl url = userResponse.request().url().resolve(location);// 如果 url 为 null 说明协议不支持 HttpUrl,那么就不做重定向if (url == null) return null;// 如果重定向的两个 url 的 scheme 不同,并且配置了 OkHttpClient 不允许// ssl 重定向(默认允许),那么就返回 null 不做重定向boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());if (!sameScheme && !client.followSslRedirects()) return null;Request.Builder requestBuilder = userResponse.request().newBuilder();// 如果请求方式允许有请求体,即不是 GET、HEAD 请求if (HttpMethod.permitsRequestBody(method)) {// 只有 PROPFIND 请求才能带着请求体进行重定向,其它请求的 maintainBody 都是 falsefinal boolean maintainBody = HttpMethod.redirectsWithBody(method);if (HttpMethod.redirectsToGet(method)) {// 除了 PROPFIND 请求之外都改成 GET 请求requestBuilder.method("GET", null);} else {RequestBody requestBody = maintainBody ? userResponse.request().body() : null;requestBuilder.method(method, requestBody);}// 不保持请求体,就要将请求头中关于请求体的数据删掉if (!maintainBody) {requestBuilder.removeHeader("Transfer-Encoding");requestBuilder.removeHeader("Content-Length");requestBuilder.removeHeader("Content-Type");}}// 跨主机重定向要删除身份验证请求头。这可能会让应用层感到烦恼,因为应用层没有办法保留这些请求头if (!sameConnection(userResponse, url)) {requestBuilder.removeHeader("Authorization");}return requestBuilder.url(url).build();// 408:服务器等待客户端发送的请求时间过长,超时。实际中用的很少,像 HAProxy 这种服务器会用这个状态码,// 不需要修改请求,只需再申请一次即可。case HTTP_CLIENT_TIMEOUT:// 客户端配置了不进行重试if (!client.retryOnConnectionFailure()) {return null;}// 请求体实现了 UnrepeatableRequestBody 接口,不重试if (userResponse.request().body() instanceof UnrepeatableRequestBody) {return null;}// 如果本次响应本身就是一个重新请求,并且上一次是 408,那么就不再重试了if (userResponse.priorResponse() != null&& userResponse.priorResponse().code() == HTTP_CLIENT_TIMEOUT) {return null;}// 如果服务器告诉我们需要在多久后重试,那框架就不管了if (retryAfter(userResponse, 0) > 0) {return null;}// 返回原来的请求,没有修改,也就是重试了return userResponse.request();// 503:由于超载或系统维护,服务器暂时的无法处理客户端的请求。延时的长度可包含在服务器的 Retry-After 头信息中case HTTP_UNAVAILABLE:if (userResponse.priorResponse() != null&& userResponse.priorResponse().code() == HTTP_UNAVAILABLE) {// We attempted to retry and got another timeout. Give up.return null;}// 如果服务器返回的 Retry-After 是 0,也就是立即重试的意思,框架才重新请求if (retryAfter(userResponse, Integer.MAX_VALUE) == 0) {return userResponse.request();}return null;default:return null;}}

我们看到重定向主要就是根据 Response 中返回的 Http 的状态码做相应的处理,如果对状态码不是很熟悉,可以参考HTTP 状态码,至少要清楚状态码的分类:

分类 分类描述
1** 信息,服务器收到请求,需要请求者继续执行操作
2** 成功,操作被成功接收并处理
3** 重定向,需要进一步的操作以完成请求
4** 客户端错误,请求包含语法错误或无法完成请求
5** 服务器错误,服务器在处理请求的过程中发生了错误

我们根据处理方式的相似程度,分组介绍以上响应码,顺序就采用 switch 代码块中书写的响应码顺序。

重定向中的响应码

401 & 407

如果你使用了 Http 代理服务器,那么在做重定向时,代理服务器会给你返回一个 407 的状态码,我们看到在 HTTP_PROXY_AUTH 这个 case 下,最终返回的是 OkHttpClient 的 proxyAuthenticator 的 authenticate() 的结果。也就是说,如果你挂了代理,那么你需要通过 proxyAuthenticator() 给 OkHttpClient 配置代理服务器的鉴权信息,在请求头中添加 Proxy-Authorization:

 OkHttpClient client = new OkHttpClient.Builder().proxyAuthenticator(new Authenticator() {@Nullable@Overridepublic Request authenticate(Route route, Response response) throws IOException {// 参考 Authenticator 接口上的注释就知道为何要这样写了String credential = Credentials.basic("userName", "password");Request request = response.request().newBuilder().addHeader("Proxy-Authorization", credential).build();return request;}}).build();

与 407 类似,状态码 401 是服务器需要授权,比如某些接口需要登录才能使用(当然这种方式不安全,现在基本上已经不用这种方式了),此时需要在请求头中添加 Authorization,配置的方式与 407 类似,通过 OkHttpClient.Builder 的 authenticator() 进行配置,不再赘述。

300 ~ 303、307 & 308

如果响应码是 3 开头,说明响应头中有一个 Location 字段指向另一个 URL,意思是服务器让你重定向,向 Location 中的 URL 发起请求。

307 和 308 分别表示临时重定向和永久重定向,如果请求方式不是 GET 或 POST,那么用户代理绝对不能自动重定向该请求。于是在 HTTP_PERM_REDIRECT 和 HTTP_TEMP_REDIRECT 两个 case 下就只是对请求方式进行了判断,如果不是 GET 或 POST 就直接返回 null 表示不进行重定向。

而如果请求方式验证没有问题,会继续向下走,做与 300 ~ 303 相同的处理:

  • 先看 OkHttpClient 是否允许重定向,,如不允许,直接返回 null
  • 接下来从 Response 中取出 Location 字段,并将 Location 指定的 URL 封装进 HttpUrl
  • 如果当前 URL 与重定向的 URL 的 scheme 不同,且 OkHttpClient 不允许 SSL 重定向,返回 null
  • 在 Response 携带的 Request 的基础上新建请求体,除了 PROPFIND 方式可以保留原有请求体进行重定向外,其它请求全部修改为 GET,并且移除原请求头中的 Transfer-Encoding、Content-Length 和 Content-Type 字段
  • 如果是跨主机重定向,要删除身份验证请求头 Authorization
  • 最后通过构造者模式新建这个重定向的 Request 并返回

408 & 503

这两个状态码其实跟重定向没啥关系,应该是重试,只不过之前在 2.1 节说的重试,是因为发送请求时出现了异常而进行重试,而这两个状态码是服务器返回的状态,分别告诉我们客户端连接超时、服务器当前不可用,那 OkHttp 框架针对这两个状态码的处理就是重试。

对于 408 的处理,有一部分跟之前的重试处理逻辑是一样的,就不多说了,主要看看 retryAfter() 是干啥的,因为该方法在下面处理 503 的时候也用到了:

 /*** 根据响应头中的 Retry-After 字段,返回当前距离下一次重试需要的时间。当前会忽略 * HTTP 的日期,并且假设任何非 int 型的 0 都是延迟*/private int retryAfter(Response userResponse, int defaultDelay) {String header = userResponse.header("Retry-After");if (header == null) {return defaultDelay;}// https://tools.ietf.org/html/rfc7231#section-7.1.3// currently ignores a HTTP-date, and assumes any non int 0 is a delayif (header.matches("\\d+")) {return Integer.valueOf(header);}return Integer.MAX_VALUE;}

实际上就是返回一个延迟的值,表示过多长时间之后再重试。在处理 503 的时候,只有这个延迟是 0 时,才会返回一个 Request 进行处理,否则就不管了。

最后对这些响应码做一个总结:

响应码 说明 重定向条件
407 代理需要授权,如付费代理,需要验证身份 通过proxyAuthenticator获得到了Request。
例: 添加 Proxy-Authorization 请求头
401 服务器需要授权,如某些接口需要登陆才能使用 (不安全,基本上没用了) 通过authenticator获得到了Request。
例: 添加 Authorization 请求头
300、301、 302、303、 307、308 重定向响应 307与308必须为GET/HEAD请求再继续判断
1、用户允许自动重定向(默认允许)
2、能够获得 Location 响应头,并且值为有效url
3、如果重定向需要由HTTP到https间切换,需要允许(默认允许)
408 请求超时。服务器觉得你太慢了 1、用户允许自动重试(默认允许)
2、本次请求的结果不是 响应408的重试结果
3、服务器未响应Retry-After(稍后重试),或者响应Retry-After: 0。
503 服务不可用 1、本次请求的结果不是 响应503的重试结果
2、服务器明确响应 Retry-After: 0,立即重试

重试与重定向拦截器只会对 Response 做处理,而不会处理 Request。而接下来要说的桥接拦截器,对 Request 和 Response 都会做出处理。

三、桥接拦截器

BridgeInterceptor 是连接应用程序和服务器的桥梁,我们发出的请求将会经过它的处理才能正确的发给服务器,比如设置请求内容长度,编码,gzip 压缩,Cookie 等,获取响应后保存 Cookie 等操作。

 @Overridepublic Response intercept(Interceptor.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");}}// 如果请求头中没有配置 Host,则补全if (userRequest.header("Host") == null) {requestBuilder.header("Host", hostHeader(userRequest.url(), false));}// 如果请求头中没有配置 Connection,框架会自动为我们申请一个长连接,如果服务器同意// 长连接,那么会返回一个 Connection:Keep-Alive,否则返回 Connection:closeif (userRequest.header("Connection") == null) {requestBuilder.header("Connection", "Keep-Alive");}// 如果请求头没配置 Accept-Encoding 和 Range 字段,则用 gzip 格式补全 Accept-Encodingboolean transparentGzip = false;if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {transparentGzip = true;requestBuilder.header("Accept-Encoding", "gzip");}// 补全请求头中的 Cookie 字段,cookieJar 在创建桥接责任链对象时传入List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());if (!cookies.isEmpty()) {requestBuilder.header("Cookie", cookieHeader(cookies));}// 补全请求头中的 User-Agent 字段,即请求者的用户信息,如操作系统、浏览器等if (userRequest.header("User-Agent") == null) {requestBuilder.header("User-Agent", Version.userAgent());}// 补全请求头后创建一个新的 Request 对象交给下一个责任链处理Response networkResponse = chain.proceed(requestBuilder.build());// 读取 Set-Cookie 响应头并调用接口告知用户,在下次请求时会读取对应的数据设置进请求头HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());Response.Builder responseBuilder = networkResponse.newBuilder().request(userRequest);// 解压。如果响应头 Content-Encoding 为 gzip,则使用 GzipSource 包装解析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();}

补全的请求头列表:

请求头 说明
Content-Type 请求体类型,如:application/x-www-form-urlencoded
Content-Length / Transfer-Encoding 请求体解析方式
Host 请求的主机站点
Connection: Keep-Alive 保持长连接
Accept-Encoding: gzip 接受响应支持 gzip 压缩
Cookie cookie 身份辨别
User-Agent 请求的用户信息,如:操作系统、浏览器等

在补全请求头后会将新产生的 Request 传递给责任链上的下一个拦截器处理,得到 Response 后会做两件事:

  1. 保存 cookie,下次请求时会读取对应的数据设置进请求头,默认的 CookieJar 不提供实现
  2. 解压,如果响应头 Content-Encoding 为 gzip,则使用 GzipSource 包装便于解析

CookieJar 接口需要我们实现从 Response 保存 cookie 和为 Request 加载 cookie 的方法,其内部有一个默认不接收任何 cookie 的实现:

public interface CookieJar {/*** A cookie jar that never accepts any cookies.*/CookieJar NO_COOKIES = new CookieJar() {@Overridepublic void saveFromResponse(HttpUrl url, List<Cookie> cookies) {}@Overridepublic List<Cookie> loadForRequest(HttpUrl url) {return Collections.emptyList();}};/*** Saves {@code cookies} from an HTTP response to this store according to this jar's policy.** <p>Note that this method may be called a second time for a single HTTP response if the response* includes a trailer. For this obscure HTTP feature, {@code cookies} contains only the trailer's* cookies.*/void saveFromResponse(HttpUrl url, List<Cookie> cookies);/*** Load cookies from the jar for an HTTP request to {@code url}. This method returns a possibly* empty list of cookies for the network request.*/List<Cookie> loadForRequest(HttpUrl url);
}

如果我们自己实现了一个 CookieJar,需要通过 cookieJar() 配置给 OkHttpClient 。

总结一下,桥接拦截器的作用:

  1. 对用户构建的 Request 进行添加或者删除相关头部信息,以转化成能够真正进行网络请求的 Request
  2. 将 Request 交给下一个拦截器处理并获取 Response
  3. 保存 Cookie,以便在下次请求时会读取对应的数据设置进请求头
  4. 如果 Response 经过了 GZIP 压缩,那就需要解压,再构建成用户可用的 Response 并返回

四、缓存拦截器

CacheInterceptor 的使用有一个前提,就是必须是 GET 请求。在发出 GET 请求前,判断是否命中缓存,如果命中则可以不通过网络发送请求,而是直接使用缓存中的响应。正是因为这样,使用缓存可以减少流量消耗,同时加快响应速度。

OkHttpClient 默认不会使用缓存,需要通过 cache() 进行配置,将缓存持久化保存在本地:

     // 缓存文件File cacheFile = new File("xxxx");// 缓存文件的最大容量long maxSize = 1024 * 1024;OkHttpClient client = new OkHttpClient.Builder().cache(new Cache(cacheFile,maxSize)).build();

缓存拦截器面临的最重要的问题是:发送网络请求,还是使用缓存?这个问题的判断是由“缓存策略” CacheStrategy 决定的,其实它也影响着这个 CacheInterceptor 的工作逻辑,所以我们先来看下 CacheStrategy。

4.1 缓存策略

在 CacheStrategy 中有两个成员 networkRequest 和 cacheResponse:

 CacheStrategy(Request networkRequest, Response cacheResponse) {this.networkRequest = networkRequest;this.cacheResponse = cacheResponse;}

分别表示是否需要发起网络请求、能否使用缓存,二者共同决定了最终会采用哪种缓存策略:

networkRequest cacheResponse 说明
Null Not Null 直接使用缓存
Null Null 请求失败,OkHttp 框架会返回 504
Not Null Null 向服务器发起请求
Not Null Not Null 发起请求,若得到响应为 304(无修改),则更新缓存响应并返回

即 networkRequest 存在则优先发起网络请求,否则使用 cacheResponse 缓存,若都不存在则请求失败!

源码实现部分涉及到的流程和细节比较繁杂,特别是涉及到 Http 状态码处理的内容,可能会让人看的抓狂,所以看到这里知道缓存策略的四种取值情况就可以越过源码去到 4.2 节看缓存拦截器具体的工作流程,看如何使用缓存策略了。

看源码实现,其实 CacheStrategy 的内部类 Factory 才是真正的缓存策略的制定者:

 public static class Factory {/*** nowMillis:时间戳* request:寻求缓存的请求* cacheResponse:request 对应的缓存的响应*/public Factory(long nowMillis, Request request, Response cacheResponse) {this.nowMillis = nowMillis;this.request = request;this.cacheResponse = cacheResponse;if (cacheResponse != null) {// cacheResponse 对应的请求发出的本地时间以及接收到这个响应的本地时间this.sentRequestMillis = cacheResponse.sentRequestAtMillis();this.receivedResponseMillis = cacheResponse.receivedResponseAtMillis();// 保存 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);}}}}}

在 Factory 的构造方法中,主要是将缓存的响应头中的部分字段的值保存到 Factory 对应的成员变量中,这些响应头的含义如下:

响应头 说明 例子
Date 消息发送的时间 Date: Sat, 18 Nov 2028 06:17:41 GMT
Expires 资源过期的时间 Expires: Sat, 18 Nov 2028 06:17:41 GMT
Last-Modified 资源最后修改时间 Last-Modified: Fri, 22 Jul 2016 02:57:17 GMT
ETag 资源在服务器的唯一标识 ETag: “16df0-5383097a03d40”
Age 服务器用缓存响应请求,该缓存从产生到现在经过多长时间(秒) Age: 3825683
Cache-Control - -

Cache-Control 可以同时存在与请求头和响应头。

保存好信息,接下来就要进入策略制定了,入口在 get(),它会给我们返回一个符合要求的 CacheStrategy:

 public CacheStrategy get() {// 获取 CacheStrategyCacheStrategy candidate = getCandidate();// 检查 candidate 合理性:如果允许使用缓存,那么 networkRequest 一定为 null。但是 if 中只使用缓存,// networkRequest 又不为 null,这就是一个冲突的条件,那就干脆算作请求失败,返回一个双空 CacheStrategyif (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;}

真正产生 CacheStrategy 的是 getCandidate(),该方法会假设 Request 允许使用网络(意思不考虑是否因为配置等原因造成网络不可使用,我就只是根据规则判断是否需要发送网络请求返回给使用者,至于网络是否能用,你拿着我给的结果自己判断去):

 private CacheStrategy getCandidate() {// 1.没找到 request 对应的缓存,那就进行网络请求if (cacheResponse == null) {return new CacheStrategy(request, null);}// 2.如果是 Https 请求,但是缓存中没有对应的握手信息,那么缓存无效,需要进行网络请求if (request.isHttps() && cacheResponse.handshake() == null) {return new CacheStrategy(request, null);}// 3.通过检查响应码检查 cacheResponse 不应该被缓存的情况,此时要进行网络请求if (!isCacheable(cacheResponse, request)) {return new CacheStrategy(request, null);}// 4.请求头中满足以下三个条件之一,需要进行网络请求:// 1)包含 Cache-Control: no-cache,表示客户端不使用缓存/验证缓存有效性?// 2)包含 If-Modified-Since: 时间,值一般为 Date 或 lastModified ,服务器没有在指定的时间后修改请求对应资源,返回304(无修改)// 3)包含 If-None-Match:标记,值一般为 Etag,将其与请求对应资源的 Etag 值进行比较;如果匹配,返回304CacheControl requestCaching = request.cacheControl();if (requestCaching.noCache() || hasConditions(request)) {return new CacheStrategy(request, null);}// 5.资源是否不变?如是,则请求的响应内容将一直不会改变,使用缓存CacheControl responseCaching = cacheResponse.cacheControl();if (responseCaching.immutable()) {return new CacheStrategy(null, cacheResponse);}// 6.响应的缓存有效期long ageMillis = cacheResponseAge();long freshMillis = computeFreshnessLifetime();if (requestCaching.maxAgeSeconds() != -1) {freshMillis = Math.min(freshMillis, SECONDS.toMillis(requestCaching.maxAgeSeconds()));}long minFreshMillis = 0;if (requestCaching.minFreshSeconds() != -1) {minFreshMillis = SECONDS.toMillis(requestCaching.minFreshSeconds());}long maxStaleMillis = 0;if (!responseCaching.mustRevalidate() && requestCaching.maxStaleSeconds() != -1) {maxStaleMillis = SECONDS.toMillis(requestCaching.maxStaleSeconds());}if (!responseCaching.noCache() && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) {Response.Builder builder = cacheResponse.newBuilder();if (ageMillis + minFreshMillis >= freshMillis) {builder.addHeader("Warning", "110 HttpURLConnection \"Response is stale\"");}long oneDayMillis = 24 * 60 * 60 * 1000L;if (ageMillis > oneDayMillis && isFreshnessLifetimeHeuristic()) {builder.addHeader("Warning", "113 HttpURLConnection \"Heuristic expiration\"");}return new CacheStrategy(null, builder.build());}// Find a condition to add to the request. If the condition is satisfied, the response body// will not be transmitted.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);}

这个方法很长,简单的情况看注释即可,下面解释几个复杂一点的情况。

是否可以缓存

在第 3 中情况中,使用 isCacheable() 对响应码和响应头进行了检查:

 public static boolean isCacheable(Response response, Request request) {// 总是通过网络获取不可缓存的响应码(RFC 7231 section 6.1),此实现不支持缓存部分内容switch (response.code()) {case HTTP_OK: // 200case HTTP_NOT_AUTHORITATIVE: // 203case HTTP_NO_CONTENT: // 204case HTTP_MULT_CHOICE: // 300case HTTP_MOVED_PERM: // 301case HTTP_NOT_FOUND: // 404case HTTP_BAD_METHOD: // 405case HTTP_GONE: // 410case HTTP_REQ_TOO_LONG: // 414case HTTP_NOT_IMPLEMENTED: // 501case StatusLine.HTTP_PERM_REDIRECT: // 308// 以上代码可以缓存,除非被请求头/响应头中的 cache-control:nostore 禁止了break;case HTTP_MOVED_TEMP: // 302case StatusLine.HTTP_TEMP_REDIRECT: // 307// 302 和 307,如果响应头中的 Expires 不为 null,或者 CacheControl 的值为// max-age、public、private 三者之一才有机会去继续判断是否存在// cache-control:nostore,否则直接返回 false 表示不可缓存if (response.header("Expires") != null|| response.cacheControl().maxAgeSeconds() != -1|| response.cacheControl().isPublic()|| response.cacheControl().isPrivate()) {break;}// Fall-through.default:// All other codes cannot be cached.return false;}// 请求头或响应头只要有一个的 Cache-Control 的值为 no-store,都要返回 false 不进行缓存return !response.cacheControl().noStore() && !request.cacheControl().noStore();}

对于 200, 203, 204, 300, 301, 404, 405, 410, 414, 501, 308 这几个响应码,只需要检查请求头或响应头中是否有 Cache-Control 字段,且值包含 no-store,如果有则不可缓存,否则可以缓存。

而 302 和 307 这两个重定向响应码,在向上面那些响应码一样检查 Cache-Control 是否有 no-store 之前,需要先检查响应头中是否有允许缓存的响应头:

  1. 响应头中存在 Expires 字段,可以缓存
  2. 响应头中的 Cache-Control 字段满足下列三个条件之一即可缓存:
    • 存在资源最大有效时间 max-age
    • 值为 public,表明该资源可以被任何用户缓存,比如客户端,代理服务器等都可以缓存资源
    • 值为 private,表明该资源只能被单个用户缓存,默认是 private

需要响应头中的 Expires 不为 null,或者 CacheControl 的值为 max-age、public、private 三者之一,然后再像上面那些响应码那样检查 。

总结一下能否缓存的判定条件:

  1. 响应码不是以上提到的这些,不可缓存
  2. 响应码为 302、307 时,响应头中若不包含可以缓存的字段,不可缓存
  3. 请求头或响应头中包含 Cache-Control: no-store 时不可缓存

用户请求配置

通过 Request 的 cacheControl() 可以得到用户对请求的缓存配置 CacheControl,如果给 CacheControl 配置了不使用缓存,或者请求头中包含 If-Modified-Since、If-None-Match 两个字段之一,就不可使用缓存:

     private static boolean hasConditions(Request request) {return request.header("If-Modified-Since") != null || request.header("If-None-Match") != null;}

这两个字段的含义:

请求头 说明
If-Modified-Since:[Time] 值一般为 Date 或 lastModified,如果服务器没有在指定的时间后修改请求对应资源,会返回 304(无修改)
If-None-Match:[Tag] 值一般为 Etag,将其与请求对应资源的 Etag 值进行比较;如果匹配,则返回 304

如果用户请求头中包含了这些内容,那就必须向服务器发起请求。OkHttp 并不会缓存 304 的响应,而是直接返回给使用者。

响应的缓存有效期

响应的缓存只是在一定时间内有效,并不是永久有效,判定缓存是否在有效期的公式:

缓存存活时间 < 缓存新鲜度 - 缓存最小新鲜度 + 过期后继续使用时长

“缓存新鲜度-缓存最小新鲜度”代表了缓存真正有效的时间。总体来说,只要不忽略缓存并且缓存未过期,则使用缓存。

4.2 缓存流程

按照缓存策略:原则是如果 networkRequest 存在则优先发起网络请求,否则使用 cacheResponse,若都不存在则请求失败进行拦截器逻辑处理:

 @Overridepublic Response intercept(Interceptor.Chain chain) throws IOException {// 1.检查请求是否有对应的 Response 缓存Response cacheCandidate = cache != null? cache.get(chain.request()): null;long now = System.currentTimeMillis();// 2.由 CacheStrategy 决定是发送请求还是使用缓存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) {// 如果 networkRequest 和 cacheResponse 都为空会返回一个 504 响应码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();}// 3.交给下一个责任链处理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) {// 服务器返回 304,那就使用缓存作为本次请求的响应,但是需要更新时间等数据if (networkResponse.code() == HTTP_NOT_MODIFIED) {// 更新 cacheResponse 的发送、接收时间等数据,但是响应体并没有动,还用原来的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 {cache.remove(networkRequest);} catch (IOException ignored) {// The cache cannot be written.}}}return response;}

五、连接拦截器

ConnectInterceptor 打开与目标服务器的连接,该连接可能是新建的,也可能是从连接池中复用的,并执行下一个拦截器。连接拦截器的 intercept() 的内容本身非常简单,只有 10 行左右的代码,它的重点都集中在连接池上,所以我们主要看看连接池。

OkHttp 的连接池是在 ConnectionPool 中实现的:

 /*** 默认的连接池会保持 5 个空闲连接,如果它们闲置超过 5 分钟会被回收*/public ConnectionPool() {this(5, 5, TimeUnit.MINUTES);}// maxIdleConnections 类似于前面说过的线程池的核心线程数public ConnectionPool(int maxIdleConnections, long keepAliveDuration, TimeUnit timeUnit) {this.maxIdleConnections = maxIdleConnections;this.keepAliveDurationNs = timeUnit.toNanos(keepAliveDuration);// Put a floor on the keep alive duration, otherwise cleanup will spin loop.if (keepAliveDuration <= 0) {throw new IllegalArgumentException("keepAliveDuration <= 0: " + keepAliveDuration);}}

向连接池中存入连接:

 private static final Executor executor = new ThreadPoolExecutor(0 /* corePoolSize */,Integer.MAX_VALUE /* maximumPoolSize */, 60L /* keepAliveTime */, TimeUnit.SECONDS,new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp ConnectionPool", true));private final Deque<RealConnection> connections = new ArrayDeque<>();void put(RealConnection connection) {assert (Thread.holdsLock(this));if (!cleanupRunning) {cleanupRunning = true;// 清理连接池executor.execute(cleanupRunnable);}connections.add(connection);}// 清理连接池的任务private final Runnable cleanupRunnable = new Runnable() {@Overridepublic void run() {while (true) {// 下一次执行清理动作最快需要多少时间long waitNanos = cleanup(System.nanoTime());if (waitNanos == -1) return;if (waitNanos > 0) {// 用纳秒控制会更加精确long waitMillis = waitNanos / 1000000L;waitNanos -= (waitMillis * 1000000L);synchronized (ConnectionPool.this) {try {ConnectionPool.this.wait(waitMillis, (int) waitNanos);} catch (InterruptedException ignored) {}}}}}};

连接会被添加到 connections 这个双向队列中,在添加之前会检查 cleanupRunnable 这个清理连接池的任务是否在运行,如果没有,会用线程池运行这个任务。

 /*** 维护连接池的方法,会将超过 keep-alive 时间或到达了设置的空闲时间的连接* 回收掉。返回 -1 表示不需要更多的清理工作,而如果返回一个 long 型的纳秒* 时间,表示在下一次调用这个方法之前,需要线程休眠的时长*/long cleanup(long now) {int inUseConnectionCount = 0;int idleConnectionCount = 0;RealConnection longestIdleConnection = null;long longestIdleDurationNs = Long.MIN_VALUE;// Find either a connection to evict, or the time that the next eviction is due.synchronized (this) {for (Iterator<RealConnection> i = connections.iterator(); i.hasNext(); ) {RealConnection connection = i.next();// 如果当前连接正在被使用,就记录正在被使用的连接数量if (pruneAndGetAllocationCount(connection, now) > 0) {inUseConnectionCount++;continue;}// 否则记录闲置连接数idleConnectionCount++;// 计算当前连接已经闲置了多久,并且保存闲置时间最长的连接与时长long idleDurationNs = now - connection.idleAtNanos;if (idleDurationNs > longestIdleDurationNs) {longestIdleDurationNs = idleDurationNs;longestIdleConnection = connection;}}// 遍历结束,找到了闲置时间最长的那个连接,如果它的闲置时长超过了我们设置的保活时间,// 或者空闲连接数量超过了最大空闲连接数,就移除该连接。if (longestIdleDurationNs >= this.keepAliveDurationNs|| idleConnectionCount > this.maxIdleConnections) {connections.remove(longestIdleConnection);} else if (idleConnectionCount > 0) {// 空闲连接数大于0,即将有连接被移除,返回该连接被移除需要等待的时间return keepAliveDurationNs - longestIdleDurationNs;} else if (inUseConnectionCount > 0) {// 能走到这个条件说明 idleConnectionCount<=0,即没有空闲连接,此时只要 inUseConnectionCount>0// 就说明所有连接都在使用中,因此你至少需要等待一个保活时间的时长,才需要过来检查是否有连接需要被移除return keepAliveDurationNs;} else {// No connections, idle or in use.cleanupRunning = false;return -1;}}// 关闭掉被移除的连接closeQuietly(longestIdleConnection.socket());// Cleanup again immediately.return 0;}

从连接池中取出连接:

 @NullableRealConnection get(Address address, StreamAllocation streamAllocation, Route route) {assert (Thread.holdsLock(this));// 遍历连接池,只有连接的配置(dns/代理/域名等等)一致才可以取出复用for (RealConnection connection : connections) {if (connection.isEligible(address, route)) {streamAllocation.acquire(connection, true);return connection;}}return null;}

RealConnection 的 isEligible() 用来判断复用条件:

 public boolean isEligible(Address address, @Nullable Route route) {// 连接池中的连接都在使用,则不能复用// If this connection is not accepting new streams, we're done.if (allocations.size() >= allocationLimit || noNewStreams) return false;// 地址(包括 ip、dns、代理、证书、端口等等)不同,不能复用// If the non-host fields of the address don't overlap, we're done.if (!Internal.instance.equalsNonHost(this.route.address(), address)) return false;// 如果 Host 也相同,那就可以复用了// If the host exactly matches, we're done: this connection can carry the address.if (address.url().host().equals(this.route().address().url().host())) {return true; // This connection is a perfect match.}// At this point we don't have a hostname match. But we still be able to carry the request if// our connection coalescing requirements are met. See also:// https://hpbn.co/optimizing-application-delivery/#eliminate-domain-sharding// https://daniel.haxx.se/blog/2016/08/18/http2-connection-coalescing/// 1. This connection must be HTTP/2.if (http2Connection == null) return false;// 2. The routes must share an IP address. This requires us to have a DNS address for both// hosts, which only happens after route planning. We can't coalesce connections that use a// proxy, since proxies don't tell us the origin server's IP address.if (route == null) return false;if (route.proxy().type() != Proxy.Type.DIRECT) return false;if (this.route.proxy().type() != Proxy.Type.DIRECT) return false;if (!this.route.socketAddress().equals(route.socketAddress())) return false;// 3. This connection's server certificate's must cover the new host.if (route.address().hostnameVerifier() != OkHostnameVerifier.INSTANCE) return false;if (!supportsUrl(address.url())) return false;// 4. Certificate pinning must match the host.try {address.certificatePinner().check(address.url().host(), handshake().peerCertificates());} catch (SSLPeerUnverifiedException e) {return false;}return true; // The caller's address can be carried by this connection.}

连接拦截器说白了就是帮我们拿到一个 Socket。

六、请求服务器拦截器

CallServerInterceptor,将 Request 中的请求数据拼接成一个报文并发送出去,在收到服务器返回响应后,解析其中的数据并封装到 Response 中。

 @Overridepublic Response intercept(Interceptor.Chain chain) throws IOException {RealInterceptorChain realChain = (RealInterceptorChain) chain;HttpCodec httpCodec = realChain.httpStream();StreamAllocation streamAllocation = realChain.streamAllocation();RealConnection connection = (RealConnection) realChain.connection();Request request = realChain.request();long sentRequestMillis = System.currentTimeMillis();// 写请求头,HttpCodec 有两个实现类 Http1Codec、Http2CodecrealChain.eventListener().requestHeadersStart(realChain.call());httpCodec.writeRequestHeaders(request);realChain.eventListener().requestHeadersEnd(realChain.call(), request);Response.Builder responseBuilder = null;// 请求方式需要携带请求体(即抛出 GET、HEADER),并且请求体不为空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,if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {// 发出请求头httpCodec.flushRequest();realChain.eventListener().responseHeadersStart(realChain.call());// 如果服务器同意接收该请求,会响应 100,无响应体,得到的 responseBuilder 为空responseBuilder = httpCodec.readResponseHeaders(true);}// 服务器同意接收请求,才开始写请求体并发送出去if (responseBuilder == null) {// Write the request body if the "Expect: 100-continue" expectation was met.realChain.eventListener().requestBodyStart(realChain.call());long contentLength = request.body().contentLength();CallServerInterceptor.CountingSink requestBodyOut =new CallServerInterceptor.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()) {// 服务器不接收,并且连接不支持多路复用的(其实就是看是不是 Http2,Http2 支持,Http1 不支持),关闭连接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 responseresponseBuilder = 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);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(httpCodec.openResponseBody(response)).build();}if ("close".equalsIgnoreCase(response.request().header("Connection"))|| "close".equalsIgnoreCase(response.header("Connection"))) {streamAllocation.noNewStreams();}if ((code == 204 || code == 205) && response.body().contentLength() > 0) {throw new ProtocolException("HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());}return response;}

Expect: 100-continue 一般用于上传大容量请求体或者需要验证时,会先询问服务器是否愿意接收请求体,此时服务器可能会有三种操作:

  1. 服务器同意接收,会返回 100 给客户端,然后客户端才可以发出请求体
  2. 服务器返回其它响应码,框架会直接返回给用户
  3. 服务器忽略此请求头,客户端一直无法读取到服务器的应答,导致抛出超时异常

OkHttp(二)—— 拦截器相关推荐

  1. okhttp之拦截器

    okhttp的拦截器是项目中的精髓代码,今天我们来具体分析一下,base4.9.1版本,首先列一下okhttp的类图用来加深印象 我们已经知道拦截器是在RealCall中添加的: val interc ...

  2. OKHttp五大拦截器

    文章目录 [1]五大拦截器总体概述 一.责任链设计模式 ①定义: ②为什么要使用责任链模式 [2]拦截器的工作流程 一.默认的5大拦截器有哪些? [3]RetryAndFollowUpIntercep ...

  3. okhttp初识拦截器

    拦截器流程: 简单回顾同步 / 异步: 同步请求就是执行请求的操作是阻塞式,直到HTTP响应返回. 异步请求就类似于非阻塞式的请求,它的执行结果一般都是通过接口回调的方式告知调用者. okHttp拦截 ...

  4. OkHttp3源码分析二 拦截器 上

    在上一篇中,我们大概知道了OkHttp进行网络请求的大概的流程: 按着流程,一个一个的分析. RetryAndFollowUpInterceptor 构造方法: public RetryAndFoll ...

  5. 好用的自定义Okhttp日志拦截器

    Okhttp中自带的日志拦截器 HttpLoggingInterceptor 实在是不好用,日志太多太乱,所以想要有好看.简洁的日志打印就要靠自定义了,下面分享我参照 HttpLoggingInter ...

  6. okhttp缓存拦截器应用

    之前只是听说缓存,今天我自己也尝试了一下 ,运用了单例模式,我其实对这些都不是很熟悉,我就是学到哪记录到哪,如果有不对的地方,希望各位指教. package com.silent.fuxiokhttp ...

  7. Android OkHttp 源码解析 - 拦截器

    一.前言 看一下 RealCall 中的拦截器排序: Response getResponseWithInterceptorChain() throws IOException {// Build a ...

  8. Android OKHttp 可能你从来没用过的拦截器 【实用推荐】

    前言 在平时开发中,你有没有下面这样的困扰呢? 场景一 明明是服务端的接口数据错误,而QA(测试)第一个找到的可能是客户端开发的你,为什么这个页面出现错误了? 而作为客户端开发的你,可能要拿出测试机连 ...

  9. OKHttp 可能你从来没用过这样的拦截器

    码个蛋(codeegg) 第 835 次推文 作者:北斗星_And 博客:https://juejin.im/post/5ddddd2a6fb9a07161483fb2 码妞看世界 世界比树枝错综复杂 ...

最新文章

  1. 第一个Servlet和Jsp
  2. 「图像分类」从数据集和经典网络开始
  3. Java集合源码分析(二)ArrayList
  4. CLR类型设计之属性
  5. window 查找 java 进程中占用cpu比较高的线程
  6. Python有哪些是必须学的运算符?
  7. Jenkins的入门(一)安装
  8. Kafka面试题与答案全套整理
  9. vue获取input的属性_vuejs 中如何优雅的获取 Input 值
  10. java语言sql接口_Java语言SQL接口
  11. java内部类选择题_java内部类使用总结
  12. 【C语言】编译预处理和宏(附带##介绍)
  13. 第九章php与数据交互,利用ajax实现与php数据交互,并局部刷新页面
  14. mysql中float、double、decimal的区别
  15. https抓包_浅谈HTTPS抓包原理,为什么Charles能够抓取HTTPS报文?
  16. HDU3954 线段树(区间更新 + 点更新)
  17. Win XP 精简版安装SQL Server
  18. DLNA和UPnP是什么关系?通俗解释
  19. 计算机设计贺卡教案,《运用Word制作电子贺卡》教学设计
  20. 你知道域名劫持的重要性吗? 教你防范网站被域名劫持

热门文章

  1. 监控数据库的作用是什么呢?
  2. 微信小程序如何使用阿里字体图标(用法非常简单适用web)
  3. sqlmap 常用命令
  4. python实现cnn特征提取_使用PyTorch提取CNNs图像特征
  5. python日期计算器 青少年编程电子学会python编程等级考试二级真题解析2021年12月
  6. JS实现植物大战僵尸小游戏,代码记录及效果展示
  7. SpringBoot整合emqx(MQTT)解决循坏依赖
  8. 【软件使用】VSCode的服务器和github同步
  9. Linux入门学习日志(三)
  10. python-pygame与pymunk-台球游戏