How to set timeout in Retrofit library?
public class ApiClient {
private static Retrofit retrofit = null;
private static final Object LOCK = new Object();
public static void clear() {
synchronized (LOCK) {
retrofit = null;
}
}
public static Retrofit getClient() {
synchronized (LOCK) {
if (retrofit == null) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.connectTimeout(40, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.client(okHttpClient)
.baseUrl(Constants.WEB_SERVICE)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
}
public static RequestBody plain(String content) {
return getRequestBody("text/plain", content);
}
public static RequestBody getRequestBody(String type, String content) {
return RequestBody.create(MediaType.parse(type), content);
}
}
@FormUrlEncoded
@POST("architect/project_list_Design_files")
Call<DesignListModel> getProjectDesign(
@Field("project_id") String project_id);
@Multipart
@POST("architect/upload_design")
Call<BoqListModel> getUpLoadDesign(
@Part("user_id") RequestBody user_id,
@Part("request_id") RequestBody request_id,
@Part List<MultipartBody.Part> image_file,
@Part List<MultipartBody.Part> design_upload_doc);
private void getMyProjectList()
{
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<MyProjectListModel> call = apiService.getMyProjectList("",Sorting,latitude,longitude,Search,Offset+"",Limit);
call.enqueue(new Callback<MyProjectListModel>() {
@Override
public void onResponse(Call<MyProjectListModel> call, Response<MyProjectListModel> response) {
try {
Log.e("response",response.body()+"");
} catch (Exception e)
{
Log.e("onResponse: ", e.toString());
}
}
@Override
public void onFailure(Call<MyProjectListModel> call, Throwable t)
{
Log.e( "onFailure: ",t.toString());
}
});
}
// file upload
private void getUpload(String path,String id)
{
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
MultipartBody.Part GalleryImage = null;
if (path!="")
{
File file = new File(path);
RequestBody reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
GalleryImage = MultipartBody.Part.createFormData("image", file.getName(), reqFile);
}
RequestBody UserId = RequestBody.create(MediaType.parse("text/plain"), id);
Call<uplod_file> call = apiService.geUplodFileCall(UserId,GalleryImage);
call.enqueue(new Callback<uplod_file>() {
@Override
public void onResponse(Call<uplod_file> call, Response<uplod_file> response) {
try {
Log.e("response",response.body()+"");
Toast.makeText(getApplicationContext(),response.body().getMessage(),Toast.LENGTH_SHORT).show();
} catch (Exception e)
{
Log.e("onResponse: ", e.toString());
}
}
@Override
public void onFailure(Call<uplod_file> call, Throwable t)
{
Log.e( "onFailure: ",t.toString());
}
});
}
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
In Kotlin :
At first you should create a OkHttp client
and add in Retrofit builder
fun create(): Retrofit {
val client = OkHttpClient.Builder()
.readTimeout(60,TimeUnit.SECONDS)
.build()
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
You can set timeouts on the underlying HTTP client. If you don't specify a client, Retrofit will create one with default connect and read timeouts. To set your own timeouts, you need to configure your own client and supply it to the RestAdapter.Builder
.
An option is to use the OkHttp client, also from Square.
1. Add the library dependency
In the build.gradle, include this line:
compile 'com.squareup.okhttp:okhttp:x.x.x'
Where x.x.x
is the desired library version.
2. Set the client
For example, if you want to set a timeout of 60 seconds, do this way for Retrofit before version 2 and Okhttp before version 3 (FOR THE NEWER VERSIONS, SEE THE EDITS):
public RestAdapter providesRestAdapter(Gson gson) {
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);
return new RestAdapter.Builder()
.setEndpoint(BuildConfig.BASE_URL)
.setConverter(new GsonConverter(gson))
.setClient(new OkClient(okHttpClient))
.build();
}
EDIT 1
For okhttp versions since 3.x.x
, you have to set the dependency this way:
compile 'com.squareup.okhttp3:okhttp:x.x.x'
And set the client using the builder pattern:
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.build();
More info in Timeouts
EDIT 2
Retrofit versions since 2.x.x
also uses the builder pattern, so change the return block above to this:
return new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
If using a code like my providesRestAdapter
method, then change the method return type to Retrofit.
More info in Retrofit 2 — Upgrade Guide from 1.9
ps: If your minSdkVersion is greater than 8, you can use TimeUnit.MINUTES
:
okHttpClient.setReadTimeout(1, TimeUnit.MINUTES);
okHttpClient.setConnectTimeout(1, TimeUnit.MINUTES);
For more details about the units, see TimeUnit.
These answers were outdated for me, so here's how it worked out.
Add OkHttp, in my case the version is 3.3.1
:
compile 'com.squareup.okhttp3:okhttp:3.3.1'
Then before building your Retrofit, do this:
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build();
return new Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();