Home > Back-end >  okHttp client gives timeout after adding callTimeout() config to it and has moments where the reques
okHttp client gives timeout after adding callTimeout() config to it and has moments where the reques

Time:02-19

after adding callTimeout() config to the okhttp client I started to get timeouts

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();

I'm not completely sure if having callTimeout configured with the same value as write and read is correct.Is it possible if read and write takes longer to trigger callTimeout()? Also another weird thing is that there are moments in which the request doesn't even reach the host

CodePudding user response:

As after adding the configurations, you are getting this exception, I am suspecting, the requested endpoint needs more time than your configured 5 seconds.

If your requested endpoint is taking more than 5 seconds (5_000 milliseconds) to get a response, you will get a timeout here with this config.

You can use postman to get the response time of your requested endpoint. If it is more than 5 seconds, you can simply configure these values accordingly. Maybe, you can use 30 seconds, instead of 5 Seconds.

I Hope, it helps.

CodePudding user response:

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.

Correct me if I'm wrong. from what I understand callTimeOut() set call timeout spans for the entire call. Eg: you set callTimeOut = 5s. if resolving DNS takes 1s, connecting 1s, write 2s, read 2s then you will get TimeOut exception. by default, callTimeOut() is set to no timeout while another default Timeouts is 10s. why do you have to set callTimeOut() to 5s? for me, I have never set callTimeOut before.

  • Related