Skip to content Skip to sidebar Skip to footer

Retrofit 2: How To Set Individual Timeouts On Specific Requests?

I have set a global timeout in my Retrofit adapter by doing OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setReadTimeout(20, TimeUnit.SECONDS); okHttpClient.setConne

Solution 1:

You can do that by creating overloaded method of your retrofit object factory method. It's maybe look like this.

publicclassRestClient {

    publicstaticfinalintDEFAULT_TIMEOUT=20;

    publicstatic <S> S createService(Class<S> serviceClass) {
        OkHttpClient.BuilderhttpClient=newOkHttpClient.Builder();
        OkHttpClientclient= httpClient.build();
        okHttpClient.setReadTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        okHttpClient.setConnectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);

        Retrofitretrofit=newRetrofit.Builder().baseUrl(BASE_URL)
            .client(client)
            .build();
        return retrofit.create(serviceClass);
    }

    publicstatic <S> S createService(Class<S> serviceClass, int timeout) {
        OkHttpClient.BuilderhttpClient=newOkHttpClient.Builder();
        OkHttpClientclient= httpClient.build();
        okHttpClient.setReadTimeout(timeout, TimeUnit.SECONDS);
        okHttpClient.setConnectTimeout(timeout, TimeUnit.SECONDS);

        Retrofitretrofit=newRetrofit.Builder().baseUrl(APIConfig.BASE_URL)
            .client(client)
            .build();
        return retrofit.create(serviceClass);
    }


}

if you want to call api with default timout, you can call it look like this.

MyAPI api = RestClient.createService(MyAPI.class);
api.notImportant();

And use the second one if you want to call api with authentication:

int timeout = 35;
MyAPI api2 = RestClient.createService(MYAPI.class, timeout);
api2.veryImportant();

Another solution is by creating different method with different OkHttpClient configuration instead of creating overloaded method. Hope this solution fix your problem.

Solution 2:

Please check this.

If you are using compile 'com.squareup.retrofit:retrofit:1.9.0' then use okhttp from same squareup lib given bellow

compile'com.squareup.okhttp:okhttp:2.7.2'

And here i have my sample code.

finalOkHttpClientokHttpClient=newOkHttpClient();
            okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
            okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);

            RestAdapterrestAdapter=newRestAdapter.Builder()
                    .setEndpoint(API)
                    .setLogLevel(RestAdapter.LogLevel.FULL)
                    .setClient(newOkClient(okHttpClient))
                    .build();

Note : 60 - retrofit will wait till 60 seconds to show timeout.

Post a Comment for "Retrofit 2: How To Set Individual Timeouts On Specific Requests?"