OkHttp中的retryOnConnectionFailure(true)方法可以实现错误重试,但不支持自定义重试次数。
1.通过自定义一个Interceptor实现错误重试次数。
1.1自定义RetryInterceptor
public class RetryInterceptor implements Interceptor
{
public int executionCount; // 最大重试次数
private long retryInterval; // 重试的间隔
RetryInterceptor(Builder builder)
{
this.executionCount = builder.executionCount;
this.retryInterval = builder.retryInterval;
}
@Override
public Response intercept(Chain chain) throws IOException
{
Request request = chain.request();
Response response = chain.proceed(request);
int retryNum = 0;
while ((response == null || !response.isSuccessful()) && retryNum <= executionCount)
{
final long nextInterval = getRetryInterval();
try
{
Thread.sleep(nextInterval);
}
catch (