Does OkHttpClient have a max retry count
There's no in built method to set the maximum limit, but you can add an interceptor like below.
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;
}
});
More detail on interceptos can be found here.
I made an workaround below:
@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;
}
According to source code of RetryAndFollowUpInterceptor
it is 20
/**
* How many redirects and auth challenges should we attempt? Chrome follows 21 redirects; Firefox,
* curl, and wget follow 20; Safari follows 16; and HTTP/1.0 recommends 5.
*/
private static final int MAX_FOLLOW_UPS = 20;
There are more docs here https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.Builder.html#retryOnConnectionFailure-boolean-
Configure this client to retry or not when a connectivity problem is encountered. By default, this client silently recovers from the following problems:
- Unreachable IP addresses. If the URL's host has multiple IP addresses, failure to reach any individual IP address doesn't fail the overall request. This can increase availability of multi-homed services.
Stale pooled connections. The ConnectionPool reuses sockets to decrease request latency, but these connections will occasionally time out.
Unreachable proxy servers. A ProxySelector can be used to attempt multiple proxy servers in sequence, eventually falling back to a direct connection.
Set this to false to avoid retrying requests when doing so is destructive. In this case the calling application should do its own recovery of connectivity failures.
But generally, I believe it is intended to retry when there is an existing stale connection, or alternate paths that can be retried. Not to retry exactly the same thing indefinitely.
Also see ConnectionSpecSelector.connectionFailed