How to set timeout in Retrofit-2.0+ android

前端 未结 4 1873
甜味超标
甜味超标 2021-02-01 01:19

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

I am using

 compile \'com.squareup.retrofit2:retrofit:2.0         


        
相关标签:
4条回答
  • 2021-02-01 01:59

    try below code, it sét timeout is 20 seconds and readTimeout is 30 seconds

     private OkHttpClient getRequestHeader() {
            OkHttpClient httpClient = new OkHttpClient();
            httpClient.setConnectTimeout(20, TimeUnit.SECONDS);
            httpClient.setReadTimeout(30, TimeUnit.SECONDS);
    
            return httpClient;
        }
    

    Then

    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)
                        .client(getRequestHeader())
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
            return retrofit;
            }
        }
    
    0 讨论(0)
  • 2021-02-01 02:00

    If you are using "com.squareup.retrofit2:retrofit:2.4.0" retrofit version > 2 then you try this one:

    private OkHttpClient getRequestHeader() 
    {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .readTimeout(60, TimeUnit.SECONDS)
            .connectTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(20, TimeUnit.SECONDS)
            .build();
    
        return okHttpClient;
    }
    
    0 讨论(0)
  • 2021-02-01 02:07

    I have used bellow like in Kotlin with MVVM Model..

    var okHttpClient: OkHttpClient? = OkHttpClient.Builder()
        .connectTimeout(60, TimeUnit.SECONDS)
        .readTimeout(60, TimeUnit.SECONDS)
        .writeTimeout(60, TimeUnit.SECONDS)
        .build()
    
    private val api = Retrofit.Builder()
        .baseUrl(baseurl)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .client(okHttpClient)
        .build()
        .create(Api::class.java);
    
    0 讨论(0)
  • 2021-02-01 02:10

    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

    0 讨论(0)
提交回复
热议问题