Okhttp3 set timeout is useless

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());
}

This is my code, I set the timeout to 5 seconds, but it still checked 20 seconds to get "error unknownhostexception" after "begin"? why is my code useless? I looked at the OKHTTP source code, the default timeout is 10 seconds (if I'm right), I'm confused.

Anyone can help, id really appreciated.

+4
source share
1 answer

OkHttp cannot interrupt long-running DNS queries right now (see https://github.com/square/okhttp/issues/95 ), but you can still 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();
+1
source

Source: https://habr.com/ru/post/1664825/


All Articles