okHttp 客户端在向其添加 callTimeout() 配置后会超时,并且有请求未到达主机的时刻

okHttp client gives timeout after adding callTimeout() config to it and has moments where the request doesn't reach the host

将 callTimeout() 配置添加到 okhttp 客户端后,我开始出现超时

Caused by: java.io.InterruptedIOException: timeout
Caused by: java.io.IOException: Canceled

OkHttpClient httpClient = new OkHttpClient.Builder()
                .callTimeout(5_000L, TimeUnit.MILLISECONDS)
                .connectTimeout(500L, TimeUnit.MILLISECONDS)
                .readTimeout(5_000L, TimeUnit.MILLISECONDS)
                .writeTimeout(5_000L, TimeUnit.MILLISECONDS)
                .build();

我不完全确定是否将 callTimeout 配置为与写入和读取相同的值 correct.Is 如果读取和写入需要更长的时间来触发 callTimeout() 是否可能? 还有一件奇怪的事情是,有些时候请求甚至没有到达主机

因为在添加配置后,你得到这个异常,我怀疑,请求的端点需要比你配置的 5 秒更多的时间。

如果您请求的端点需要超过 5 秒(5_000 毫秒)才能获得响应,您将在此配置中获得超时。

您可以使用 postman 获取您请求的端点的响应时间。如果超过 5 秒,您可以简单地相应地配置这些值。也许,你可以用 30 秒,而不是 5 秒。

希望对您有所帮助。

callTimeOut()

Sets the default timeout for complete calls. A value of 0 means no timeout, otherwise values must be between 1 and [Integer.MAX_VALUE] when converted to milliseconds. The call timeout spans the entire call: resolving DNS, connecting, writing the request body, server processing, and reading the response body. If the call requires redirects or retries all must complete within one timeout period. The default value is 0 which imposes no timeout.

如果我错了请纠正我。据我了解 callTimeOut() 为整个通话设置通话超时跨度。例如:您设置 callTimeOut = 5s。如果解析 DNS 需要 1s,连接 1s,写入 2s,读取 2s 那么你会得到 TimeOut 异常。默认情况下,callTimeOut() 设置为无超时,而另一个默认超时为 10 秒。为什么必须将 callTimeOut() 设置为 5s?对我来说,我以前从未设置过callTimeOut。