Search code examples
javaandroidretrofitokhttp

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


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


Solution

  • 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.