我在我的 Android 项目中使用 Retrofit/OkHttp (1.6)。
我没有找到任何内置的请求重试机制。在搜索更多内容时,我读到 OkHttp 似乎有静默重试。我没有看到我的任何连接(HTTP 或 HTTPS)上发生这种情况。如何使用 okclient 配置重试?
目前,我正在捕获异常并重试维护计数器变量。
对于改造 2.x;
您可以使用调用.clone() https://square.github.io/retrofit/2.x/retrofit/retrofit2/Call.html#clone克隆请求并执行它的方法。
对于改造 1.x;
您可以使用拦截器 https://github.com/square/okhttp/wiki/Interceptors。创建自定义拦截器
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();
// try the request
Response response = chain.proceed(request);
int tryCount = 0;
while (!response.isSuccessful() && tryCount < 3) {
Log.d("intercept", "Request is not successful - " + tryCount);
tryCount++;
// retry the request
response.close()
response = chain.proceed(request);
}
// otherwise just pass the original response on
return response;
}
});
并在创建 RestAdapter 时使用它。
new RestAdapter.Builder()
.setEndpoint(API_URL)
.setRequestInterceptor(requestInterceptor)
.setClient(new OkClient(client))
.build()
.create(Adapter.class);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)