Search code examples
androidretrofitretrofit2

How to set timeout in Retrofit-2.0+ android


I referred this link but I can't seem to implement for mine

I am using

 compile 'com.squareup.retrofit2:retrofit:2.0.2'
 compile 'com.squareup.retrofit2:converter-gson:2.0.2'

I am using the below code, How to set timeout for this !

public class ApiClient {

    public static final String BASE_URL = Constants.BaseURL;
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

Solution

  • Configure OkHttpClient for timeout option. Then use this as client for Retrofit.Builder.

    final OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .connectTimeout(20, TimeUnit.SECONDS)
        .writeTimeout(20, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build();
    

    Use this okHttpClient for Retrofit#Builder

    Retrofit.Builder()
        .client(okHttpClient);
    

    Official OkHttp documentation about timeout is here