android - 如何在 Android 的 Retrofit 库中设置连接超时?

标签 android retrofit retrofit2

我为我的 Android 应用程序使用了 Retrofit 库。我需要将连接超时设置为 120 秒。我能怎么做 ?

版本:

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.google.code.gson:gson:2.8.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

OperatingApiClient:

    public class OperatingApiClient {
    public static final String BASE_URL = "http://172.16.2.39/";
    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;
    }
    }

目标文件接口(interface):

public interface TargetFileApiInterface {
@GET("NNGOperating/GetTargetFileList")
Call<TargetFileApiResponse> getTargetFileList(@Query("api_key") 
String apiKey);

}

TargetFileApiResponse:

    public class TargetFileApiResponse {
    @SerializedName("TargetFileList")
    private List<TargetFile> targetfileslist;

    public TargetFileApiResponse(List<TargetFile> targetfileslist) {
        this.targetfileslist = targetfileslist;
    }

    public List<TargetFile> getTargetfileslist() {
        return targetfileslist;
    }

    public void setTargetfileslist(List<TargetFile> targetfileslist) {
        this.targetfileslist = targetfileslist;
    }
    }

最佳答案

你可以设置OkHttp的配置

OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(yourTime, TimeUnit.SECONDS)
        .writeTimeout(yourTime, TimeUnit.SECONDS)
        .readTimeout(yourTime, TimeUnit.SECONDS)
        .build();

之后,设置客户端进行改造

retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(client)
                    .build();

关于android - 如何在 Android 的 Retrofit 库中设置连接超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42324921/

相关文章:

android - 如何使用 Kotlin 协程获取 API 错误主体

android - 如何为安卓创建apk文件?

java - 为什么方法 onClick(View v) 有 View 类型参数?

android - Android 推特中的超链接消息

java - Retrofit2:如何正确检查response.body()的有效性?

java - 在 Retrofit 的 POST 请求中发送空正文

android - 如何在应用程序最小化时更新 UI

android - Kotlin 协程、改造、Android

android - OkHttp 和 Retrofit 抛出 IO : Stream 3 not progressing

android - 正在发送多个改造调用,但有些从未收到响应或错误