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秒才能在“开始”之后收到“error unknownhostexception”?为什么我的代码没用?我看过OKHTTP的源代码,默认超时是10秒(如果我是对的),我很困惑。
任何人都可以提供帮助,我非常感激。
答案 0 :(得分:2)
目前,OkHttp无法中断耗时的DNS请求(请参阅https://github.com/square/okhttp/issues/95),但是您仍然可以执行以下操作:
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();