如何在Retrofit-2.0 + Android中设置超时 [英] How to set timeout in Retrofit-2.0+ android

查看:89
本文介绍了如何在Retrofit-2.0 + Android中设置超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我引用了此链接,但是我似乎无法为我实现

我正在使用

 编译'com.squareup.retrofit2:retrofit:2.0.2'编译'com.squareup.retrofit2:converter-gson:2.0.2' 

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

 公共类ApiClient {公共静态最终字符串BASE_URL = Constants.BaseURL;私有静态Retrofit Retrofit = null;公共静态Retrofit getClient(){if(retrofit == null){Retrofit =新Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).建造();}退货改造;}} 

解决方案

配置使用此<用于retrofit#Builder的code> okHttpClient

  Retrofit.Builder().client(okHttpClient); 

有关超时的OkHttp官方文档在这里

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

解决方案

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

这篇关于如何在Retrofit-2.0 + Android中设置超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆