Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set timeout in Retrofit-2.0+ android

I referred this link but I can't seem to implement for mine

I am using

 compile 'com.squareup.retrofit2:retrofit:2.0.2'  compile 'com.squareup.retrofit2:converter-gson:2.0.2' 

I am using the below code, How to set timeout for this !

public class ApiClient {      public static final String BASE_URL = Constants.BaseURL;     private static Retrofit retrofit = null;      public static Retrofit getClient() {         if (retrofit==null) {             retrofit = new Retrofit.Builder()                     .baseUrl(BASE_URL)                     .addConverterFactory(GsonConverterFactory.create())                     .build();         }         return retrofit;     } } 
like image 765
Devrath Avatar asked May 11 '16 12:05

Devrath


People also ask

What is default timeout retrofit?

1 and Retrofit 2.1. 0, the default value for OkHttp is 10 seconds.

Why do we use retrofit in Android?

Retrofit is used to perform the following tasks: It manages the process of receiving, sending, and creating HTTP requests and responses. It alternates IP addresses if there is a connection to a web service failure. It caches responses to avoid sending duplicate requests.

What is retrofit in Android medium?

Retrofit is an open-source type-safe HTTP client library developed by Square. You can check out the Github source code. ( Link ) It is the most used and most efficient library for network requests in applications. We can import this library like this our project. We need to add this library to the dependencies section.


1 Answers

Configure OkHttpClient for timeout option. Then use this as client for Retrofit.Builder.

final OkHttpClient okHttpClient = new OkHttpClient.Builder()     .connectTimeout(20, TimeUnit.SECONDS)     .writeTimeout(20, TimeUnit.SECONDS)     .readTimeout(30, TimeUnit.SECONDS)     .build(); 

Use this okHttpClient for Retrofit#Builder

Retrofit.Builder()     .client(okHttpClient); 

Official OkHttp documentation about timeout is here

like image 181
Alex Chengalan Avatar answered Sep 24 '22 16:09

Alex Chengalan