Retrofit 2 – Handle Connection Timeout Exception

Learn to configure timeouts in android apps using retrofit 2 and OkHttp library. We will learn to configure default timeouts and custom connection timeouts in this tutorial.

1. Default timeouts

By default, Retrofit 2 uses the following timeouts:

  1. Call timeout – 0 (no timeout)
  2. Connection timeout – 10 seconds
  3. Read timeout – 10 seconds
  4. Write timeout – 10 seconds

2. Set timeouts using OkHttpClient.Builder

2.1. Timeout methods

OkHttpClient.Builder API provides 4 methods which can be used to set timeouts.

  • callTimeout(Duration duration) – Sets the default timeout for complete calls. The call timeout spans the entire call: resolving DNS, connecting, writing the request body, server processing, and reading the response body. If the call requires redirects or retries all must complete within one timeout period.

    The default value is 0 which imposes no timeout.

  • connectTimeout(Duration duration) – Sets the default connect timeout for new connections. The connect timeout is applied when connecting a TCP socket to the target host.
  • readTimeout(Duration duration) – The read timeout is applied to both the TCP socket and for individual read IO operations including on Source of the Response.
  • writeTimeout(Duration duration) – The write timeout is applied for individual write IO operations.

All above methods are overloaded methods and can accept either Duration or two parameters i.e. time out number, time unit. For example, call timeout can be configured using callTimeout(long timeout, TimeUnit unit) also.

2.2. How to set timeout

Java example code to set timeout duration in Retrofit in any android app.

String BASE_URL = "https://howtodoinjava.com/";

OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
				.callTimeout(2, TimeUnit.MINUTES)
				.connectTimeout(20, TimeUnit.SECONDS)
			    .readTimeout(30, TimeUnit.SECONDS)
			    .writeTimeout(30, TimeUnit.SECONDS);

Retrofit.Builder builder = new Retrofit.Builder()
				.baseUrl(BASE_URL)
				.addConverterFactory(SimpleXmlConverterFactory.create());

builder.client(httpClient.build());

Retrofit retrofit = builder.build();

//Create service
RssService rssService = retrofit.create(RssService.class);

3. How to handle retrofit connection timeout exception

Generally in the android app, we do not care which type of timeout error was occurred because it all boils down to slow network connection.

In app, in case of network timeouts, can check for the class of exception instance when the error finally timeouts and onFailure(Throwable t) is executed. We shall check for SocketTimeoutException and IOException, specially.

@Override
public void onFailure(Call<UserApiResponse> call, Throwable error) 
{
	if (error instanceof SocketTimeoutException) 
	{ 
    	// "Connection Timeout"; 
	} 
	else if (error instanceof IOException) 
	{ 
    	// "Timeout"; 
	} 
	else  
	{
		//Call was cancelled by user
		if(call.isCanceled()) 
		{
			System.out.println("Call was cancelled forcefully");
		} 
		else 
		{
			//Generic error handling
			System.out.println("Network Error :: " + error.getLocalizedMessage());
		}
	}
}

4. What different timeouts mean?

4.1. Call timeout

It is the sum of all the time taken to complete the request. It includes time taken in resolving DNS, establishing connection, sending request (including payload) and receiving response (including payload).

If there is some time taken in server processing that is also included in this call time.

We should configure call timeout to a large value for above said reasons.

4.2. Connect timeout

Connection timeout is the time that start from sending the request to a completed TCP handshake with the server. If Retrofit couldn’t establish the connection to the server within the set connection timeout limit, request is considered as failed.

A connection timeout may be set large for countries with bad Internet connection.

4.3. Read timeout

The read timeout is the time-out applied from the moment you have established a connection (So handshaking is done, and the connection can be used).

Specifically, if the server fails to send a byte in specified timeout period after the last byte, a read timeout error will be raised.

4.4. Write timeout

If sending a single byte takes longer than the configured write timeout limit the a read timeout error will be raised by retrofit.

We can set larger timeouts for users with bad internet connections.

Drop me your question in comments.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

1 thought on “Retrofit 2 – Handle Connection Timeout Exception”

  1. Hi, thanks for your article, but, i have not gotten this about timeouts, would you mind to explain me a little bit more ?

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.