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:

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:

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:

OkHttp Post Examples

Java REST Client Examples Using OkHttp

Basic Authentication with OkHttp Example

Upload a File with OkHttp

Download a File with OkHttp

WebSocket Client Example with OkHttp

How to Cache Response with OkHttp

0 0 vote
Article Rating