3

I am using Okhttp 2.5, 2.6, 2.7 with RxJava and Retrofit 2. I got some mysterious issue with okhttp call. When I made call with retrofit my Okhttp interceptor get called immediately while NetworkInterceptor called after 4 to 5 second. Sometime its more than 15 second, and leads SocketTimeoutExcpetion.

Please suggest, What should I do to solve this problem. Is there any thread blocking my call get executed?

2 Answers2

0

OkHttp is behaving as it should. A SocketTimeoutException happens when the server takes longer to respond than what the client is willing to wait, and it just gives up. There is a default read timeout of 10 seconds since OkHttp 2.5 (and including the new 3.0), which would explain why you're getting the exception after 15 seconds.

You can set your own timeouts to allow your server ample time to respond:

OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(20, TimeUnit.SECONDS);  // connect timeout
client.setReadTimeout(20, TimeUnit.SECONDS);     // socket timeout

Note that this doesn't handle the exception, it will still be thrown if the client doesn't receive a response in x seconds now. I would make sure to actually catch the exception. This would be an appropriate place to have your retry logic.


Since you're using RxJava with Retrofit, you could just add retry/retryWhen to your chain to catch and handle SocketTimeoutException errors, and maybe even mix in exponential backoff.

Community
  • 1
  • 1
Roth
  • 149
  • 2
  • 7
  • Roth, thanks for reply. I am using your mentioned configuration, also retryWhen. But, problem is my network connection and server is stable and I am getting sockettimeout. I also searched regarding this, some post suggest its ipv6 problem, but our server is ipv4. So, I am not sure what kind of problem is this. Did you ever face such kind of problem? My users also facing the same. – Adarsh Pandey Jan 04 '16 at 00:10
0

I know that is an old story but I seems to found a solution. To fix SocketTimeoutException you need to setup connection pool with 0 (!) idle connections!

okBuilder.connectionPool(new ConnectionPool(0, 30, TimeUnit.SECONDS));
yuliskov
  • 1,379
  • 15
  • 16