【问题标题】:How to set a delay for interceptor in okhttp?如何在okhttp中为拦截器设置延迟?
【发布时间】:2023-04-11 06:50:01
【问题描述】:

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

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;
    }
}

如何给拦截器添加延迟?

【问题讨论】:

标签: java android okhttp3


【解决方案1】:

使用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;
    }
});

【讨论】:

  • 拦截方法可以睡觉吗?
  • @AlexKlimashevsky 没有
  • 如果您的线程处于休眠状态,您无法取消您发送的请求,直到它在正常情况下唤醒。
猜你喜欢
  • 2020-05-24
  • 2019-03-03
  • 2020-09-18
  • 2015-03-23
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多