versi okhttp: 3.11.0
atau lebih tinggi
dari kode sumber okhttp
/**
* 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
dapat berupa nilai di bawah ini
TimeUnit.NANOSECONDS
TimeUnit.MICROSECONDS
TimeUnit.MILLISECONDS
TimeUnit.SECONDS
TimeUnit.MINUTES
TimeUnit.HOURS
TimeUnit.DAYS
contoh kode
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();
}
Diperbarui
Saya telah menambahkan api baru ke okhttp dari versi 3.12.0
, Anda dapat mengatur batas waktu seperti ini:
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(Duration.ofSeconds(5))/*timeout: 5 seconds*/
.build();
CATATAN: Ini membutuhkan API 26+ jadi jika Anda mendukung versi Android yang lebih lama, terus gunakan (5, TimeUnit.SECONDS)
.