如何禁用与 OkHttp 的一个连接的重试?

How to disable retries for one connection with OkHttp?

我正在使用 OkHttp 并希望在特定 api 调用上禁用连接重试。这是正确的做法吗?:

mMyGlobalClient = new OkHttpClient();

....

public void makeConnection(...) {

    OkHttpClient client = null;
    if (disableRetries) {
        OkHttpClient clone = mMyGlobalClient.clone();
        clone.setRetryOnConnectionFailure(false);
        client = clone;
    } else {
        client = mMyGlobalClient;
    }

    client.newCall(...);
}

思路来源于此post:

https://github.com/square/okhttp/pull/1259#issue-53157152

Most applications won't want to disable retry globally. Instead, use clone() to get an OkHttpClient for a specific, non-idempotent request, then configure that client with the setting.

我想禁用此调用的重试的原因是,如果它被我的服务器处理两次,它可能具有破坏性:

https://github.com/square/okhttp/pull/1259#issuecomment-68430264

谢谢

是的,这是正确的方法。

顺便说一句,如果不介意,可以写得简单一点

mMyGlobalClient = new OkHttpClient();

....

public void makeConnection(...) {

    OkHttpClient client = null;
    if (disableRetries) {
        client = mMyGlobalClient.clone();
        client.setRetryOnConnectionFailure(false);
    } else {
        client = mMyGlobalClient;
    }

    client.newCall(...);
}

使用call.cancel();

final Call call = client.newCall(request);

如果要限制重试次数,可以使用:

if (responseCount(response) >= 3) {
    call.cancel(); // If we've failed 3 times, give up.
}

另外,我已经在retrofit2中解决了这个问题

为了防止重试,您必须对 OkHttpClient 使用 .retryOnConnectionFailure(false) 方法。

示例代码:

OkHttpClient okHttpClient= null;
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(2, TimeUnit.MINUTES)
                .readTimeout(2, TimeUnit.MINUTES)
                .writeTimeout(2, TimeUnit.MINUTES)
                .retryOnConnectionFailure(false)
                .cache(null)//new Cache(sContext.getCacheDir(),10*1024*1024)
                .build();

在之前的版本中有一些错误并在 retrofit:2.1.0

之后修复

所以你应该使用更新版本的 retrofit2 和 okhttp3:

implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.okhttp3:okhttp:3.4.1' 

问题讨论:

https://github.com/square/okhttp/pull/1259#issuecomment-68430264