Java 如何在okhttp中设置拦截器的延迟?
假设我们需要在出现异常时重试请求:Java 如何在okhttp中设置拦截器的延迟?,java,android,okhttp3,Java,Android,Okhttp3,假设我们需要在出现异常时重试请求: 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
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;
}
});
OkHttpClient=new-OkHttpClient();
setConnectTimeout(连接超时为毫秒,时间单位为毫秒);
setReadTimeout(读取超时时间为毫秒,时间单位为毫秒);
client.interceptors().add(新的Interceptor()){
@凌驾
公共响应拦截(链)引发IOException{
Request=chain.Request();
响应=空;
布尔响应k=false;
int tryCount=0;
而(!responseOK&&tryCount<3){
试一试{
系统时钟。睡眠(3000);
响应=链。继续(请求);
responseOK=response.issusccessful();
}捕获(例外e){
Log.d(“拦截”,“请求未成功-”+tryCount);
}最后{
tryCount++;
}
}
//否则,只需将原始响应传递给
返回响应;
}
});
在intercept method上睡觉可以吗?@AlexKlimashevsky noDo你真的想重复你的请求,还是担心万一互联网出现问题,请求可能会失败@我想重复一遍