How to set timeout in Retrofit Android?

Member

by kelley , in category: Other , a year ago

How to set timeout in Retrofit Android?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by khalil_murazik , a year ago

@kelley 

To set a timeout in Retrofit, you can use the readTimeout and connectTimeout options in the OkHttpClient object that you use to build your Retrofit instance. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
OkHttpClient okHttpClient = new OkHttpClient.Builder()
   .readTimeout(30, TimeUnit.SECONDS)
   .connectTimeout(30, TimeUnit.SECONDS)
   .build();

Retrofit retrofit = new Retrofit.Builder()
   .baseUrl(BASE_URL)
   .client(okHttpClient)
   .addConverterFactory(GsonConverterFactory.create())
   .build();


This will set the read timeout to 30 seconds and the connect timeout to 30 seconds. The read timeout is the amount of time the client will wait to read data from the server, while the connect timeout is the amount of time the client will wait to establish a connection with the server.


Note that these timeouts apply to both HTTP requests and responses. If either the request or response takes longer than the specified timeout, Retrofit will cancel the request and trigger a SocketTimeoutException.