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秒(如果我是对的),我很困惑。
任何人都可以提供帮助,我非常感谢您。
最佳答案
目前,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();
关于android - Okhttp3设置超时是没有用的,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41319976/