Retrofit 2 – Handle Connection Timeout Exception

1,836 阅读3分钟

Retrofit 2 – Handle Connection Timeout Exception

Retrofit 2 – Handle Connection Timeout Exception

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.

    设置完整调用的默认超时时间。包括:DNS解析,连接,写入请求体,服务端处理,读取响应体。如果调用需要重定向或者重试,所有调用必须要在一个超时期限内完成。

  • 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.

    连接超时时间,为新连接设置超时时间。该时间用在TCP连接到指定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.

    读取超时时间,用在TCP套接字和单个IO读取操作,包括响应源。

  • writeTimeout(Duration duration) – The write timeout is applied for individual write IO operations.

    写入超时,写超时用在单个IO操作。

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.

这是完整请求所花费时间之和。包括解析DNS,连接,发请求,接收响应。包括有效载荷,即对用户的有用的数据。

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.

连接时间是从发请求到和服务端完整的TCP握手。如果不能在限定时间内连接,则认为请求失败。

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 !!