Raj*_*ajV 13 android okhttp okhttp3
我正在为OkHttpClient设置重试连接失败选项.
client = new OkHttpClient();
client.setRetryOnConnectionFailure(true);
Run Code Online (Sandbox Code Playgroud)
我想知道它会继续尝试多少次.查看源代码,我没有看到任何最大限制.如何配置客户端在几次尝试后停止尝试?
配置此客户端是否在遇到连接问题时重试.默认情况下,此客户端会从以下问题中无提示地恢复:
- 无法访问的IP地址.如果URL的主机具有多个IP地址,则无法访问任何单个IP地址不会使整个请求失败.这可以提高多宿主服务的可用性.
陈旧的汇集连接.ConnectionPool重用套接字来减少请求延迟,但这些连接偶尔会超时.
无法访问的代理服务器.ProxySelector可用于按顺序尝试多个代理服务器,最终回退到直接连接.
将此设置为false以避免在执行此操作具有破坏性时重试请求.在这种情况下,调用应用程序应该自己恢复连接故障.
但一般来说,我认为它应该在存在现有陈旧连接或可以重试的备用路径时重试.不要无限期地重试完全相同的事情.
另请参见ConnectionSpecSelector.connectionFailed
没有内置方法来设置最大限制,但您可以添加一个拦截器,如下所示。
client.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// try the request
Response response = chain.proceed(request);
int tryCount = 0;
int maxLimit = 3; //Set your max limit here
while (!response.isSuccessful() && tryCount < maxLimit) {
Log.d("intercept", "Request failed - " + tryCount);
tryCount++;
// retry the request
response = chain.proceed(request);
}
// otherwise just pass the original response on
return response;
}
});
Run Code Online (Sandbox Code Playgroud)
小智 6
我做了下面的解决方法:
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// try the request
Response response = doRequest(chain,request);
int tryCount = 0;
while (response == null && tryCount <= RetryCount) {
String url = request.url().toString();
url = switchServer(url);
Request newRequest = request.newBuilder().url(url).build();
tryCount++;
// retry the request
response = doRequest(chain,newRequest);
}
if(response == null){//important ,should throw an exception here
throw new IOException();
}
return response;
}
private Response doRequest(Chain chain,Request request){
Response response = null;
try{
response = chain.proceed(request);
}catch (Exception e){
}
return response;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13390 次 |
| 最近记录: |