OkHttp 调用超时包括或不包括拦截器重试
OkHttp call timeout inclusive or exclusive of interceptor retries
我正在尝试使用 OkHttpClient 进行 HTTP 调用。如果我看到 SocketTimeoutExceptions,我正在尝试在客户端上实施重试。这是我拥有的:
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// try the request
Response response = null;
int tryCount = 1;
while (tryCount <= MAX_TRY_COUNT) {
try {
response = chain.proceed(request);
break;
} catch (Exception e) {
if (!NetworkUtils.isNetworkAvailable()) {
// if no internet, dont bother retrying request
throw e;
}
if ("Canceled".equalsIgnoreCase(e.getMessage())) {
// Request canceled, do not retry
throw e;
}
if (tryCount >= MAX_TRY_COUNT) {
// max retry count reached, giving up
throw e;
}
try {
// sleep delay * try count (e.g. 1st retry after 3000ms, 2nd after 6000ms, etc.)
Thread.sleep(RETRY_BACKOFF_DELAY * tryCount);
} catch (InterruptedException e1) {
throw new RuntimeException(e1);
}
tryCount++;
}
}
// otherwise just pass the original response on
return response;
}
})
.callTimeout(5000)
.build()
我感到困惑的部分是 - 5000 毫秒超时是针对单次重试,还是包含重试?
没关系,在这里找到了答案 - https://square.github.io/okhttp/4.x/okhttp/okhttp3/-ok-http-client/-builder/call-timeout/
“如果调用需要重定向或重试,则所有调用都必须在一个超时期限内完成。”
我正在尝试使用 OkHttpClient 进行 HTTP 调用。如果我看到 SocketTimeoutExceptions,我正在尝试在客户端上实施重试。这是我拥有的:
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// try the request
Response response = null;
int tryCount = 1;
while (tryCount <= MAX_TRY_COUNT) {
try {
response = chain.proceed(request);
break;
} catch (Exception e) {
if (!NetworkUtils.isNetworkAvailable()) {
// if no internet, dont bother retrying request
throw e;
}
if ("Canceled".equalsIgnoreCase(e.getMessage())) {
// Request canceled, do not retry
throw e;
}
if (tryCount >= MAX_TRY_COUNT) {
// max retry count reached, giving up
throw e;
}
try {
// sleep delay * try count (e.g. 1st retry after 3000ms, 2nd after 6000ms, etc.)
Thread.sleep(RETRY_BACKOFF_DELAY * tryCount);
} catch (InterruptedException e1) {
throw new RuntimeException(e1);
}
tryCount++;
}
}
// otherwise just pass the original response on
return response;
}
})
.callTimeout(5000)
.build()
我感到困惑的部分是 - 5000 毫秒超时是针对单次重试,还是包含重试?
没关系,在这里找到了答案 - https://square.github.io/okhttp/4.x/okhttp/okhttp3/-ok-http-client/-builder/call-timeout/
“如果调用需要重定向或重试,则所有调用都必须在一个超时期限内完成。”