Skip to content

Instantly share code, notes, and snippets.

@devrath
Created May 6, 2021 13:00
Show Gist options
  • Save devrath/e86d591e0e03732f5050bc8a798c60b6 to your computer and use it in GitHub Desktop.
Save devrath/e86d591e0e03732f5050bc8a798c60b6 to your computer and use it in GitHub Desktop.
Retry mechanism for OKHTTP
package com.mpl.network.modules.interceptors;
import android.os.Handler;
import android.util.Log;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class RetryInterceptor implements Interceptor {
private static final String TAG = "NetworkLib: " + "RetryInterceptor";
private static final int NUMBER_OF_RETRIES = 4;
private static final double RETRY_DELAY = 300;
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// try the request
final Response[] response = {chain.proceed(request)};
int tryCount = 0;
while (!response[0].isSuccessful() && tryCount < NUMBER_OF_RETRIES) {
int expDelay = (int) (RETRY_DELAY * Math.pow(2, Math.max(0, NUMBER_OF_RETRIES - 1)));
tryCount++;
new Handler().postDelayed(() -> {
try {
response[0] = chain.call().clone().execute();
} catch (IOException e) {
e.printStackTrace();
}
}, expDelay);
}
// otherwise just pass the original response on
return response[0];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment