Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 545
angryd Avatar asked Dec 25 '16 09:12

angryd


1 Answers

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();
like image 182
Dmitry Zenovich Avatar answered Sep 29 '22 20:09

Dmitry Zenovich