I am developing app using OkHttp library and my trouble is I cannot find how to set connection timeout and socket timeout.
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
The read timeout is the timeout on waiting to read data1. If the server (or network) fails to deliver any data <timeout> seconds after the client makes a socket read call, a read timeout error will be raised.
From the client side, the “read timed out” error happens if the server is taking longer to respond and send information. This could be due to a slow internet connection, or the host could be offline. From the server side, it happens when the server takes a long time to read data compared to the preset timeout.
The default timeout is infinite. By default RestTemplate uses SimpleClientHttpRequestFactory and that in turn uses HttpURLConnection.
As of OkHttp3 you can do this through the Builder like so
client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
You can also view the recipe here.
For older versions, you simply have to do this
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(15, TimeUnit.SECONDS); // connect timeout
client.setReadTimeout(15, TimeUnit.SECONDS); // socket timeout
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
Be aware that value set in setReadTimeout is the one used in setSoTimeout on the Socket internally in the OkHttp Connection class.
Not setting any timeout on the OkHttpClient is the equivalent of setting a value of 0 on setConnectTimeout or setReadTimeout and will result in no timeout at all. Description can be found here.
As mentioned by @marceloquinta in the comments setWriteTimeout can also be set.
As of version 2.5.0 read / write / connect timeout values are set to 10 seconds by default as mentioned by @ChristerNordvik. This can be seen here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With