OkHttpClient是否具有最大重试次数

Raj*_*ajV 13 android okhttp okhttp3

我正在为OkHttpClient设置重试连接失败选项.

client = new OkHttpClient();
client.setRetryOnConnectionFailure(true);
Run Code Online (Sandbox Code Playgroud)

我想知道它会继续尝试多少次.查看源代码,我没有看到任何最大限​​制.如何配置客户端在几次尝试后停止尝试?

Yur*_*mke 8

这里有更多的文档https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.Builder.html#retryOnConnectionFailure-boolean-

配置此客户端是否在遇到连接问题时重试.默认情况下,此客户端会从以下问题中无提示地恢复:

  • 无法访问的IP地址.如果URL的主机具有多个IP地址,则无法访问任何单个IP地址不会使整个请求失败.这可以提高多宿主服务的可用性.
  • 陈旧的汇集连接.ConnectionPool重用套接字来减少请求延迟,但这些连接偶尔会超时.

  • 无法访问的代理服务器.ProxySelector可用于按顺序尝试多个代理服务器,最终回退到直接连接.

将此设置为false以避免在执行此操作具有破坏性时重试请求.在这种情况下,调用应用程序应该自己恢复连接故障.

但一般来说,我认为它应该在存在现有陈旧连接或可以重试的备用路径时重试.不要无限期地重试完全相同的事情.

另请参见ConnectionSpecSelector.connectionFailed


Pre*_*ola 6

没有内置方法来设置最大限制,但您可以添加一个拦截器,如下所示。

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;
        int maxLimit = 3; //Set your max limit here

        while (!response.isSuccessful() && tryCount < maxLimit) {

            Log.d("intercept", "Request failed - " + tryCount);

            tryCount++;

            // retry the request
            response = chain.proceed(request);
        }

        // otherwise just pass the original response on
        return response;
    }
});
Run Code Online (Sandbox Code Playgroud)

有关拦截器的更多详细信息可以在此处找到。

  • TCP 连接失败意味着无法发送 HTTP 请求或获得响应。我不确定状态代码如何会是 4xx。 (2认同)

小智 6

我做了下面的解决方法:

@Override
public Response intercept(Chain chain) throws IOException {
  Request request = chain.request();
  // try the request
  Response response = doRequest(chain,request);
  int tryCount = 0;
  while (response == null && tryCount <= RetryCount) {
    String url = request.url().toString();
    url = switchServer(url);
    Request newRequest = request.newBuilder().url(url).build();
    tryCount++;
    // retry the request
    response = doRequest(chain,newRequest);
  }
  if(response == null){//important ,should throw an exception here
      throw new IOException();
  }
  return response;
}

private Response doRequest(Chain chain,Request request){
  Response response = null;
  try{
      response = chain.proceed(request);
  }catch (Exception e){
  }
  return response;
}
Run Code Online (Sandbox Code Playgroud)