如何在Retrofit-2.0 + android中设置超时

时间:2016-05-11 12:00:54

标签: android retrofit retrofit2

我提到this link,但我似乎无法为我实施

我正在使用

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

我正在使用以下代码,如何为此设置超时!

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

4 个答案:

答案 0 :(得分:74)

为超时选项配置OkHttpClient。然后将其用作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

答案 1 :(得分:8)

尝试下面的代码,它timeout是20秒而readTimeout是30秒

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

        return httpClient;
    }

然后

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

答案 2 :(得分:0)

如果您使用的是“ com.squareup.retrofit2:retrofit:2.4.0”改造版本> 2,请尝试以下操作:

private OkHttpClient getRequestHeader() 
{
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .readTimeout(60, TimeUnit.SECONDS)
        .connectTimeout(60, TimeUnit.SECONDS)
        .writeTimeout(20, TimeUnit.SECONDS)
        .build();

    return okHttpClient;
}

答案 3 :(得分:0)

我已经在像Kotlin这样的MVVM模型中使用了波纹管。

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