1. Introduction

This short tutorial is going to cover how to set timeouts with Unirest for Java, a simplified, lightweight HTTP request library built and maintained by Mashape.

Unirest for Java allows us to set timeouts for its HTTP clients, and this is useful for us to deal with a popular issue of the client-server model is the network partitions issue. And we can use timeouts to fail a call when its peer is unreachable.

Let’s see the signature method in the Unirest class which can be used to set timeouts:

There are 2 timeout parameters we can set are:

  • Connection timeout: The timeout until a connection with the server is established (in milliseconds), and the default value is 10000
  • Socket timeout: The timeout to receive data (in milliseconds), and the default is 60000

We can set any of these timeouts to zero to disable the timeout.

2. Set Timeouts with Unirest for Java example

2.1. Library dependency

The only one dependency for this example is the unirest-java, version 1.4.9

2.2. Example code

Let’s see an example method that set the timeouts with Unirest for Java:

We have just set connection timeout with 60000 milliseconds, socket timeout with 30000 milliseconds.

3. Conclusion

The tutorial has illustrated how to set timeouts with Unirest for Java. This is useful when we want to fail a call if we have an issue with the network.

4. References

Java REST Client Example

Java REST Client Using Unirest Java API


0 0 vote
Article Rating