在使用okHttp的时候我们经常会使用超时设置:如下:
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.dns(new xDns(5))
.build();
但是在某些情况下,eg:域名解析不了。我们设置的这些超时值不管用,往往需要几十秒之后get/post之后才返回错误。所以此时我们就需要设置一下dns解析超时,关于okhttp的dns解析超时网上很多方法,这里我使用最简答的:okhttp.dns接口:
public class xDns implements Dns {
private long timeout = 5;
public xDns(long timeout){
this.timeout = timeout;
}
@Override
public List<InetAddress> lookup(String hostname) throws UnknownHostException {
if(hostname == null){
throw new UnknownHostException("host name is null");
}
else{
try {
FutureTask<List<InetAddress>> task = new FutureTask<>(
new Callable<List<InetAddress>>() {
@Override
public List<InetAddress> call() throws Exception {
return Arrays.asList(InetAddress.getAllByName(hostname));
}
});
new Thread(task).start();
return task.get(timeout, TimeUnit.SECONDS);
} catch (Exception var4) {
UnknownHostException unknownHostException =
new UnknownHostException("Unable to resolve host " + hostname);
unknownHostException.initCause(var4);
throw unknownHostException;
}
}
}
}
这样就可以很好的规避dns解析超时问题了。
博客参考:https://blog.youkuaiyun.com/quwei3930921/article/details/85336552