I am using the okhttp3 and retrofit as the android project request framework, and i have a application scene below:
There are two servers in our project with two domain;what we want to do is when connect to one server failed then we reconnect with another server in the one request,so we use the okhttp3 Interceptor like below:
public Response intercept(Chain chain) {
Request request = chain.request();
Response response = chain.proceed(request);
int tryCount = 0;//retry times
int RetryCount = 3;
while (!response.isSuccessful() && tryCount <= RetryCount) {
String url = request.url().toString();
if (!Util.checkNULL(FirstIP) && !Util.checkNULL(SecondIP)) {
if (url.contains(FirstIP)) {//change url
url = url.replace(FirstIP, SecondIP);
} else if (url.contains(SecondIP)) {
url = url.replace(SecondIP, FirstIP);
}
Request newRequest = response.request().newBuilder().url(url).build();//recreate request
tryCount++;//add request count
response = chain.proceed(newRequest);//retry the request
} else {
response = chain.proceed(request);
}
}
return response;
}
But there is an error with this sentence:
Response response = chain.proceed(request);
This sentence will throw exception when the url can't be connected,so this will not make the retry work as expected, is there any workaround about this?Thanks in advance!