2

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!

1 Answers1

0

I make an workaround like 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;
}