我在我的应用程序中使用Retrofit库,我想设置60秒的超时。Retrofit有办法做到这一点吗?

我这样设置Retrofit:

RestAdapter restAdapter = new RestAdapter.Builder()
    .setServer(BuildConfig.BASE_URL)
    .setConverter(new GsonConverter(gson))
    .build();

如何设置超时时间?


当前回答

这些答案对我来说已经过时了,所以这就是它是如何发挥作用的。

添加OkHttp,在我的情况下,版本是3.3.1:

compile 'com.squareup.okhttp3:okhttp:3.3.1'

然后在构建您的Retrofit之前,做以下工作:

OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
    .connectTimeout(60, TimeUnit.SECONDS)
    .readTimeout(60, TimeUnit.SECONDS)
    .writeTimeout(60, TimeUnit.SECONDS)
    .build();
return new Retrofit.Builder()
    .baseUrl(baseUrl)
    .client(okHttpClient)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

其他回答

在Kotlin中,您可以为retrofit2配置超时by

创建OkHttpClient对象(默认值为10秒)

val okHttpClient = OkHttpClient.Builder()
    .connectTimeout(30, TimeUnit.SECONDS)
    .writeTimeout(30, TimeUnit.SECONDS)
    .readTimeout(30, TimeUnit.SECONDS)
    .build()

然后将此对象添加到您的改造生成器中

val retrofit = Retrofit.Builder()
    .addConverterFactory(ScalarsConverterFactory.create())
    .client(okHttpClient)
    .baseUrl(BASE_URL)
    .build()

并从这个包中导入TimeUnit

import java.util.concurrent.TimeUnit
public class ApiClient {
    private static Retrofit retrofit = null;
    private static final Object LOCK = new Object();

    public static void clear() {
        synchronized (LOCK) {
            retrofit = null;
        }
    }

    public static Retrofit getClient() {
        synchronized (LOCK) {
            if (retrofit == null) {

                Gson gson = new GsonBuilder()
                        .setLenient()
                        .create();

                OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                        .connectTimeout(40, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .writeTimeout(60, TimeUnit.SECONDS)
                        .build();

                // Log.e("jjj", "=" + (MySharedPreference.getmInstance().isEnglish() ? Constant.WEB_SERVICE : Constant.WEB_SERVICE_ARABIC));
                retrofit = new Retrofit.Builder()
                        .client(okHttpClient)
                        .baseUrl(Constants.WEB_SERVICE)
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .build();
            }
            return retrofit;
        }`enter code here`

    }

    public static RequestBody plain(String content) {
        return getRequestBody("text/plain", content);
    }

    public static RequestBody getRequestBody(String type, String content) {
        return RequestBody.create(MediaType.parse(type), content);
    }
}


-------------------------------------------------------------------------


    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

您可以在底层HTTP客户机上设置超时。如果您没有指定客户端,Retrofit将创建一个具有默认连接和读取超时的客户端。要设置自己的超时,需要配置自己的客户机并将其提供给RestAdapter.Builder。

一种选择是使用OkHttp客户端,同样来自Square。

1. 添加库依赖项

在构建中。Gradle,包括这一行:

compile 'com.squareup.okhttp:okhttp:x.x.x'

其中x.x.x为所需的库版本号。

2. 设置客户端

例如,如果你想设置一个60秒的超时,在版本2之前的Retrofit和版本3之前的Okhttp(对于更新的版本,请参阅编辑):

public RestAdapter providesRestAdapter(Gson gson) {
    final OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
    okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);

    return new RestAdapter.Builder()
        .setEndpoint(BuildConfig.BASE_URL)
        .setConverter(new GsonConverter(gson))
        .setClient(new OkClient(okHttpClient))
        .build();
}

编辑1

对于3.x以后的okhttp版本。X,你必须这样设置依赖项:

compile 'com.squareup.okhttp3:okhttp:x.x.x'

并使用构建器模式设置客户端:

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

更多信息在超时


编辑2

2.x以来的更新版本。X也使用构建器模式,因此将上面的返回块更改为:

return new Retrofit.Builder()
    .baseUrl(BuildConfig.BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(okHttpClient)
    .build();

如果使用类似于我的providesRestAdapter方法的代码,则将方法返回类型更改为Retrofit。

更多信息在改造2 -从1.9升级指南


ps:如果你的minSdkVersion大于8,你可以使用TimeUnit。分钟:

okHttpClient.setReadTimeout(1, TimeUnit.MINUTES);
okHttpClient.setConnectTimeout(1, TimeUnit.MINUTES);

有关单位的详细信息,请参见TimeUnit。

我使用Retrofit 1.9来获取XML。

public class ServicioConexionRetrofitXML {

    public static final String API_BASE_URL = new GestorPreferencias().getPreferencias().getHost();
    public static final long tiempoMaximoRespuestaSegundos = 60;
    public static final long tiempoMaximoLecturaSegundos = 100;
    public static final OkHttpClient clienteOkHttp = new OkHttpClient();


    private static RestAdapter.Builder builder = new RestAdapter.Builder().
            setEndpoint(API_BASE_URL).
            setClient(new OkClient(clienteOkHttp)).setConverter(new SimpleXMLConverter());


    public static <S> S createService(Class<S> serviceClass) {
        clienteOkHttp.setConnectTimeout(tiempoMaximoRespuestaSegundos, TimeUnit.SECONDS);
        clienteOkHttp.setReadTimeout(tiempoMaximoLecturaSegundos, TimeUnit.SECONDS);
        RestAdapter adapter = builder.build();
        return adapter.create(serviceClass);
    }

}

如果你使用的是Retrofit 1.9.0和okhttp 2.6.0,添加到你的Gradle文件中。

    compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'com.squareup.okhttp:okhttp:2.6.0'
    // Librería de retrofit para XML converter (Simple) Se excluyen grupos para que no entre
    // en conflicto.
    compile('com.squareup.retrofit:converter-simplexml:1.9.0') {
        exclude group: 'xpp3', module: 'xpp3'
        exclude group: 'stax', module: 'stax-api'
        exclude group: 'stax', module: 'stax'
    }

注意:如果你需要获取JSON,只需从上面的代码中删除。

.setConverter(new SimpleXMLConverter())

对于OkHttp3用户的Retrofit1.9,这里是解决方案,

.setClient(new Ok3Client(new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build()))