android - 如何在 OkHttp 3 中为特定服务设置不同的连接超时?

标签 android retrofit retrofit2 okhttp

在我的应用程序中,除了一项服务有 3 分钟外,我的所有服务都有 60 秒连接超时。但是我只能为 OkHttp 3 设置一个超时?是否可以为该特定服务设置 180 秒?

OkHttpClient.Builder okHttpClient = newOkHttpClient.Builder()

                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)

改造:

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

最佳答案

所有 HTTP 客户端配置都在 OkHttpClient 中,包括代理设置、超时和缓存。当需要更改单个调用的配置时,调用 OkHttpClient.newBuilder()。这将返回一个构建器,它与原始客户端共享相同的连接池、调度程序和配置。

在下面的示例中,我们发出一个超时为 500 毫秒的请求和另一个超时为 3000 毫秒的请求。

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
Request request = new Request.Builder()
    .url("http://httpbin.org/delay/1") // This URL is served with a 1 second delay.
    .build();

// Copy to customize OkHttp for this request.
OkHttpClient client1 = client.newBuilder()
    .readTimeout(500, TimeUnit.MILLISECONDS)
    .build();
try (Response response = client1.newCall(request).execute()) {
  System.out.println("Response 1 succeeded: " + response);
} catch (IOException e) {
  System.out.println("Response 1 failed: " + e);
}

// Copy to customize OkHttp for this request.
OkHttpClient client2 = client.newBuilder()
    .readTimeout(3000, TimeUnit.MILLISECONDS)
    .build();
try (Response response = client2.newCall(request).execute()) {
  System.out.println("Response 2 succeeded: " + response);
} catch (IOException e) {
  System.out.println("Response 2 failed: " + e);
}
}

所以你需要为每个请求创建不同的客户端。

关于android - 如何在 OkHttp 3 中为特定服务设置不同的连接超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48563584/

相关文章:

android - Windows Phone 和 Android toasts

java - 从 gridview 中删除项目

kotlin - 数据类中的改造响应 null

android - 当应用程序在 Android 上处于前台时不显示 Amazon Pinpoint 推送通知

android - 如何在多个 Activity 中使用 Android Nearby Connections

java - 如何在 Android 中的用户输入表单上获取选中的单选按钮并将选择存储为字符串

android - OkHttp 在与改造一起使用时不会重定向 POST 请求

java - 附加 SSL 客户端证书 okhttp3 。握手失败

java - 为什么我的 'userID' 初始化为 0 而不是从 PHP 发送的内容?

android - 使用 Retrofit 响应的 NullPointerException