This tutorial is going to cover shortly how to set timeout with OkHttp, an HTTP & HTTP/2 client for Android and Java applications, powered by Square.
1. Introduction
One of the most popular issues of the client-server model is the network partitions issue. The network partitions can be due to client connectivity problems, server availability problems, or anything between. OkHttp supports us in configuring timeouts for OkHttpClient objects. The timeouts include connect timeout, read timeout and write timeout, and we can use timeouts to fail a call when its peer is unreachable.
2. Source code
In this tutorial, we’re going to use OkHttp 3.4.2, the only one related dependency we need to compile the source code is:
1 2 3 4 5 |
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.4.2</version> </dependency> |
The example source code can be found on Github or you can download it by this link: java-okhttp-examples.zip
3. Set Timeout with OkHttp
Let’s see an example method that set timeout with OkHttp as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class CrawlService { public void doCrawl(String crawlURL) throws IOException { OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(100, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS).build(); // creates new request Request request = new Request.Builder() .url(crawlURL) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } } } |
We have just set connection timeout with 100 seconds, write timeout with 10 seconds and read timeout with 20 seconds when we build the OkHttpClient. One important point is setting the timeouts with a value of 0 means no timeout.
4. Conclusion
The tutorial has just shown how to set timeout with OkHttp. This is often used when we want to fail a call if we have an issue with the network.
Below are other tutorials related to OkHttp for your references:
Java REST Client Examples Using OkHttp
Basic Authentication with OkHttp Example
WebSocket Client Example with OkHttp
How to Cache Response with OkHttp