如何禁用与OkHttp的一个连接的重试? [英] How to disable retries for one connection with OkHttp?
问题描述
我正在使用OkHttp,并且想在特定的api调用上禁用连接重试.这是正确的方法吗?:
I'm using OkHttp and want to disable connection retries on a particular api call. Is this the correct way to do it?:
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(...);
}
这个想法来自这篇文章:
The idea comes from this post:
https://github.com/square/okhttp/pull/1259#问题53157152
大多数应用程序都不想全局禁用重试.相反,使用 clone()为特定的非幂等请求获取OkHttpClient, 然后使用该设置配置该客户端.
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.
我要对此一次呼叫禁用重试的原因是,如果它被我的服务器处理两次,则可能具有破坏性:
The reason I want to disable retries for this one call is because it can be destructive if it gets handled twice by my server:
https://github.com/square/okhttp/pull/1259# issuecomment-68430264
谢谢
推荐答案
是的,这是正确的方法.
Yes, this is the right way.
顺便说一句,如果您不介意的话,可以写得简单些
By the way, if you don't mind, you could write it a little simpler
mMyGlobalClient = new OkHttpClient();
....
public void makeConnection(...) {
OkHttpClient client = null;
if (disableRetries) {
client = mMyGlobalClient.clone();
client.setRetryOnConnectionFailure(false);
} else {
client = mMyGlobalClient;
}
client.newCall(...);
}
这篇关于如何禁用与OkHttp的一个连接的重试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!