Okhttp3设置超时是没有用的 [英] Okhttp3 set timeout is useless
本文介绍了Okhttp3设置超时是没有用的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
OkHttpClient client;
client = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.build();
Request request22 = new Request.Builder()
.url("http://www.goo.com/")
.build();
Utils.myLog("-begin-");
Response response = null;
try {
response = client.newCall(request22).execute();
if (response.isSuccessful()) {
Utils.myLog("-donw-");
}
} catch (Exception e) {
e.printStackTrace();
Utils.myLog("-error-" + e.toString());
}
这是我的代码,我将超时设置为5秒,但是在开始"之后仍然需要 20秒才能收到错误unknownhostexception"?为什么我的代码没用?我看了OKHTTP的源代码,默认超时是10秒(如果我是对的),我很困惑.
This is my code, I have set timeout to 5 seconds, but it still taked 20 seconds to receive "error unknownhostexception " after "begin"? why my code is useless? I have looked the source code of OKHTTP, default timeout is 10 seconds(if I'm right), I'm confused.
任何人都可以提供帮助,我非常感谢.
Anyone can help, id really appreciated.
推荐答案
For now, OkHttp can't interrupt time-consuming DNS requests (see https://github.com/square/okhttp/issues/95), but you still can do something like this:
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.connectTimeout(15, TimeUnit.SECONDS)
.dns(hostname -> Single.fromCallable(
() -> Arrays.asList(InetAddress.getAllByName(hostname))
).timeout(15, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.onErrorReturnItem(new ArrayList<>())
.blockingGet())
.build();
这篇关于Okhttp3设置超时是没有用的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文