Why retryOnConnectionFailure(true) is a solution to OkHttp Error : java.io.IOException: unexpected end of stream

Why retryOnConnectionFailure(true) is a solution to OkHttp Error : java.io.IOException: unexpected end of stream

当我发现 this 时,这个错误已经有一段时间了。 使用 swankjesse 提供的解决方案后,错误消失了。 我似乎无法理解为什么这是一个解决方案。我在网上找不到任何东西 解释此方法解决错误的原因。

OkHttp 文档说:

retryOnConnectionFailure

Configure this client to retry or not when a connectivity problem is encountered. By default, this client silently recovers from the following problems:

Unreachable IP addresses. If the URL’s host has multiple IP addresses, failure to reach any individual IP address doesn’t fail the overall request. This can increase availability of multi-homed services.

Stale pooled connections. The ConnectionPool reuses sockets to decrease request latency, but these connections will occasionally time out.

Unreachable proxy servers. A ProxySelector can be used to attempt multiple proxy servers in sequence, eventually falling back to a direct connection.

以上是可以理解的,但并不能证明为什么这是该错误的解决方案。

提前致谢。

此标志允许 OkHttpClient 在某些条件为真时重试请求多次,这意味着它已知是安全的。如果没有此标志,客户端将 return 错误立即让客户端决定是否以及何时重试。

  private fun isRecoverable(e: IOException, requestSendStarted: Boolean): Boolean {
    // If there was a protocol problem, don't recover.
    if (e is ProtocolException) {
      return false
    }

    // If there was an interruption don't recover, but if there was a timeout connecting to a route
    // we should try the next route (if there is one).
    if (e is InterruptedIOException) {
      return e is SocketTimeoutException && !requestSendStarted
    }

    // Look for known client-side or negotiation errors that are unlikely to be fixed by trying
    // again with a different route.
    if (e is SSLHandshakeException) {
      // If the problem was a CertificateException from the X509TrustManager,
      // do not retry.
      if (e.cause is CertificateException) {
        return false
      }
    }
    if (e is SSLPeerUnverifiedException) {
      // e.g. a certificate pinning error.
      return false
    }
    // An example of one we might want to retry with a different route is a problem connecting to a
    // proxy and would manifest as a standard IOException. Unless it is one we know we should not
    // retry, we return true and try a new route.
    return true
  }

在最简单的情况下,如果我们还没有开始发送请求,那么我们知道重试一定是安全的。同样,某些响应代码(如 408)表示服务器尚未开始任何工作,因此我们可以重试。