How to set connection timeout with OkHttp

JavaTimeoutOkhttp

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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

Solution 3 - Java

For Retrofit retrofit:2.0.0-beta4 the code goes as follows:

OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(logging)
    .connectTimeout(30, TimeUnit.SECONDS)
    .readTimeout(30, TimeUnit.SECONDS)
    .writeTimeout(30, TimeUnit.SECONDS)
    .build();

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://api.yourapp.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .client(client)
    .build();

Solution 4 - Java

For Retrofit 2.0.0-beta1 or beta2, the code goes as follows:

OkHttpClient client = new OkHttpClient();

client.setConnectTimeout(30, TimeUnit.SECONDS);
client.setReadTimeout(30, TimeUnit.SECONDS);
client.setWriteTimeout(30, TimeUnit.SECONDS);

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://api.yourapp.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .client(client)
    .build();

Solution 5 - Java

Adding in gradle file and sync project:

compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.google.code.gson:gson:2.6.2'

Adding in Java class:

import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;


Builder b = new Builder();
b.readTimeout(200, TimeUnit.MILLISECONDS);
b.writeTimeout(600, TimeUnit.MILLISECONDS);
// set other properties

OkHttpClient client = b.build();

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

Solution 7 - Java

OkHttp Version:3.11.0 or higher

From okhttp source code:

/**
 * Sets the default connect timeout for new connections. A value of 0 means no timeout,
 * otherwise values must be between 1 and {@link Integer#MAX_VALUE} when converted to
 * milliseconds.
 *
 * <p>The connectTimeout is applied when connecting a TCP socket to the target host.
 * The default value is 10 seconds.
 */
public Builder connectTimeout(long timeout, TimeUnit unit) {
	connectTimeout = checkDuration("timeout", timeout, unit);
	return this;
}

unit can be any value of below

TimeUnit.NANOSECONDS
TimeUnit.MICROSECONDS
TimeUnit.MILLISECONDS
TimeUnit.SECONDS
TimeUnit.MINUTES
TimeUnit.HOURS
TimeUnit.DAYS

example code

OkHttpClient client = new OkHttpClient.Builder()
    .connectTimeout(5000, TimeUnit.MILLISECONDS)/*timeout: 5 seconds*/
    .build();

String url = "https://www.google.com";
Request request = new Request.Builder()
    .url(url)
    .build();

try {
    Response response = client.newCall(request).execute();
} catch (IOException e) {
    e.printStackTrace();
}
Updated

I have add new API to OkHttp from version 3.12.0, you can set timeout like this:

OkHttpClient client = new OkHttpClient.Builder()
    .connectTimeout(Duration.ofSeconds(5)) // timeout: 5 seconds
    .build();

NOTE: This requires API 26+ so if you support older versions of Android, continue to use (5, TimeUnit.SECONDS).

Solution 8 - Java

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

Solution 9 - Java

This worked for me:

OkHttpClient client = new OkHttpClient.Builder()
    .connectTimeout(10, TimeUnit.SECONDS)
    .readTimeout(10, TimeUnit.SECONDS)
    .writeTimeout(10, TimeUnit.SECONDS)
    .retryOnConnectionFailure(false) <-- not necessary but useful!
    .build();

Source: https://github.com/square/okhttp/issues/3553

Solution 10 - Java

If you want to customize the configuration then use the below methodology of creating OKhttpclient first and then add builder on top of it.

private final OkHttpClient client = new OkHttpClient();

// Copy to customize OkHttp for this request.
OkHttpClient client1 = client.newBuilder()
	.readTimeout(500, TimeUnit.MILLISECONDS)
	.build();
try (Response response = client1.newCall(request).execute()) {
	System.out.println("Response 1 succeeded: " + response);
} catch (IOException e) {
	System.out.println("Response 1 failed: " + e);
}

Solution 11 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkelvincerView Question on Stackoverflow
Solution 1 - JavaMiguelView Answer on Stackoverflow
Solution 2 - JavaKaizieView Answer on Stackoverflow
Solution 3 - JavaSamView Answer on Stackoverflow
Solution 4 - JavaxaxistView Answer on Stackoverflow
Solution 5 - JavaMohammad nabilView Answer on Stackoverflow
Solution 6 - JavaLeoView Answer on Stackoverflow
Solution 7 - JavaduyuanchaoView Answer on Stackoverflow
Solution 8 - JavaThiagoView Answer on Stackoverflow
Solution 9 - JavarHendersonView Answer on Stackoverflow
Solution 10 - Javasandhya murugesanView Answer on Stackoverflow
Solution 11 - JavaChaturaMView Answer on Stackoverflow