导语
使用OKHttp网络库时,遇到断网的情况,会报Unable to resolve host “xxx.xxxxx.com”:No address associated with hostname错误。正常的DNS解析流程是会先读取本地缓存,那么断网时为什么会报Unable to resolve host的错误呢?
正常DNS解析流程
正常的DNS解析流程是会先读取本地缓存,那么断网时为什么会报Unable to resolve host的错误呢?这就需要简单了解一下OKHttp的原理。
OKHTTP五大拦截器
-
RetryAndFollowUpInterceptor(重试和重定向拦截器)
第一个接触到请求,最后接触到响应;负责判断是否需要重新发起整个请求 -
BridgeInterceptor(桥接拦截器)
补全请求,并对响应进行额外处理 -
CacheInterceptor(缓存拦截器)
请求前查询缓存,获得响应并判断是否需要缓存 -
ConnectInterceptor(链接拦截器)
与服务器完成TCP连接 (Socket) -
CallServerInterceptor(请求服务拦截器)
与服务器通信;封装请求数据与解析响应数据(如:HTTP报文)
OKHttp的责任链设计模式为请求创建了一个接收者对象的链。为了避免请求发送者与多个请求处理者耦合在一起,于是将所有请求的处理者通过前一对象记住其下一个对象的引用而连成一条链,当有请求发生时,可将请求沿着这条链传递,直到有对象处理它为止。(责任链模式也叫职责链模式)
在责任链模式中,每一个对象对其下家的引用而接起来形成一条链。请求在这个链上传递,直到链上的某一个对象 决定处理此请求。客户并不知道链上的哪一个对象最终处理这个请求,系统可以在不影响客户端的 情况下动态的重 新组织链和分配责任。处理者有两个选择:承担责任或者把责任推给下家。一个请求可以最终不被任何接收端对象 所接受。
#RetryAndFollowUpInterceptor异常捕获
RetryAndFollowUpInterceptor拦截器捕获RouteException和IOException两种异常。如下:
catch (RouteException e) { //路由错误,判断是否要尝试下一个路由
// The attempt to connect via a route failed. The request will not have been sent.
if (!recover(e.getLastConnectException(), streamAllocation, false, request)) {
throw e.getFirstConnectException();
}
releaseConnection = false;
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, streamAllocation, requestSendStart在连接池中释放链接,并重试equest)) throw e;
releaseConnection = false;
continue;
}
第一次:抛出异常
在突然断网的情况下,网络请求在执行到ConnectInterceptor的newStream()方法时,仍会复用之前的dns解析结果。
但在随后的CallServerInterceptor拦截器执行到HttpCodec.finishRequest()方法后,在sink.flush()方法下会抛出IOException异常,该异常被RetryAndFollowUpInterceptor捕获后,在连接池中释放链接(ConnectionPool#connectionBecameIdle),并重试。
/**
* Notify this pool that {@code connection} has become idle. Returns true if the connection has
* been removed from the pool and should be closed.
*/
boolean connectionBecameIdle(RealConnection connection) {
assert (Thread.holdsLock(this));
if (connection.noNewStreams || maxIdleConnections == 0) {
connections.remove(connection);
return true;
} else {
notifyAll(); // Awake the cleanup thread: we may have exceeded the idle connection limit.
return false;
}
}
第二次:重试
在重试时,仍然按照拦截拦截器链的顺序,到达ConnectInterceptor的newStream()方法时,连接池里已经没有可用的链接,此时需要重新建立新的链接。
StreamAllocation#findConnection方法中,建立连接核心切入点;选择路由核心RoutSelector#next()->RoutSelector#nextProxy()->RoutSelector#resetNextInetSocketAddress()方法中调用address.dns().lookup(socketHost)方法,在该方法中重新解析dns,导致“Unable to resolve host “xxx.xxxxx.com”:No address associated with hostname”报错。