java - 如何在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;
}
}
如何为拦截器添加延迟?
解决方案
用于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;
}
});
推荐阅读
- python - Pandas Apply Lambda 导致 TypeError: 'int' object is not subscriptable
- javascript - `this.function()` 和 `function.call(this)` 之间有区别吗?
- javascript - 材料表如何将页面大小设置为全部
- javascript - 无论滚动如何,如何在鼠标滚轮上增加 1?
- android - Mqtt Android PahoClient 连接问题
- .net - 高图表Div另存为图像并在服务器路径中保存文件
- objective-c - 如何将值从 ViewController 传递到选项卡栏,然后将 Tabor 传递到 ViewController 到选项卡栏中的第一个选定项目
- c - 是否将类型分配给枚举标准 C?
- kotlin - 加号如何在 Kotlin 中指代加号函数,它是中缀函数吗?
- java - 读取 opencv_face.LBPHFaceRecognizer.getHistograms() 中的值