首页 > 解决方案 > 如何在okhttp中为拦截器设置延迟?

问题描述

假设我们需要在出现异常时重试请求:

public class TestUpInterceptor implements Interceptor {
    @Override public Response intercept(Chain chain) throws IOException {
        final Response response = chain.proceed(chain.request());
        //TODO: in case of exception retry in 3 sec
        return retryResponse;
    }
}

如何为拦截器添加延迟?

标签: javaandroidokhttp3

解决方案


用于SystemClock.sleep(3000); 延迟。

OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
client.interceptors().add(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = null;
        boolean responseOK = false;
        int tryCount = 0;

        while (!responseOK && tryCount < 3) {
            try {
                 SystemClock.sleep(3000);
                 response = chain.proceed(request);
                 responseOK = response.isSuccessful();                  
            }catch (Exception e){
                 Log.d("intercept", "Request is not successful - " + tryCount);                     
            }finally{
                 tryCount++;      
            }
        }

        // otherwise just pass the original response on
        return response;
    }
});

推荐阅读