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 OkHttpCl
For okhttp3 this has changed a bit.
Now you set up the times using the builder, and not setters, like this:
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
More info can be found in their wiki: https://github.com/square/okhttp/blob/b3dcb9b1871325248fba917458658628c44ce8a3/docs/recipes.md#timeouts-kt-java
It's changed now. Replace .Builder()
with .newBuilder()
As of okhttp:3.9.0 the code goes as follows:
OkHttpClient okHttpClient = new OkHttpClient()
.newBuilder()
.connectTimeout(10,TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(30,TimeUnit.SECONDS)
.build();
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.
As of OkHttp3 can now 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.
Like so:
//New Request
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
final OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logging)
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build();
You can set a call timeout to cover the entire cycle from resolving DNS, connecting, writing the request body, server processing, and reading the response body.
val client = OkHttpClient().newBuilder().callTimeout(CALL_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES).build()