android – 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秒才能收到“error 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();
点赞