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