how to set retrofit connections timeout unlimited? - android

I want to set Retrofit connection timeout unlimited instead of static timeout
connection.how can I do it ?
This is my code...
public static Retrofit getRetrofitInstance() {
if (RetrofitInstance==null) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(100, TimeUnit.SECONDS)
.connectTimeout(100, TimeUnit.SECONDS)
.build();
RetrofitInstance = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(okHttpClient)
.build();
}
return RetrofitInstance;
}

Retrofit does not allow developers to remove timeout completely, but you could set TimeUnit.HOURS to use big value for your timeout. For example:
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(Integer.MAX_VALUE, TimeUnit.HOURS)
.connectTimeout(Integer.MAX_VALUE, TimeUnit.HOURS)
.build();
Used Integer.MAX_VALUE for this example, which is big enough value to act as an infinite timeout.
Good luck :)

Related

How to "wait" for data from API

I have a problem,
How to wait for data from API?
I would write code like this:
List<User> userList = dataAPI.getAllUser();
I would have a list an use it wherever I want.
I don't want to Override any methods.
DataAPI:
public class DataAPI {
public DataAPI(){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
userAPI = retrofit.create(UserService.class);
public class DataAPI {
[...]
private UsertService userAPI;
public DataAPI(){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
userAPI = retrofit.create(UserService.class);
}
Observable<List<User>> getAllUser() {
return userAPI.getAllUser();
}
}
UserService
#GET("/user/all")
Observable<List<User>> getAllUser();
It could be done with rxJava, for more details: read
You just need to set timeout and increase it as you need to wait for the response coming from service. (Give priority to writeTimeout)
OkHttpClient client = new OkHttpClient.Builder();
client .connectTimeout(10, TimeUnit.SECONDS);
client .writeTimeout(30, TimeUnit.SECONDS);
client .readTimeout(40, TimeUnit.SECONDS);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.yourapp.com/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
#Kubek, what you need to do is subscribe to the observable.
What you should probably do is:
userAPI.getAllUser()
.subscribeOn(Schedulers.IO)
.observeOn(AndroidSchedulers.Main)
.subscribe(
// do some stuff
)
For documentation on how to use subscribe method, refer: http://reactivex.io/documentation/operators/subscribe.html

Retrofit: Can I re-use OkhttpClient?

I am developing an android app using external API servers.
Because I use 2 servers, I have 2 retrofit services.
In my "RemoteDataSource" class's constructor, I make the service objects like:
public RemoteDataSource() {
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build();
myService1 = new Retrofit.Builder()
.baseUrl(URL_1)
.client(okHttpClient)
.build()
.create(MyService1.class);
myService2 = new Retrofit.Builder()
.baseUrl(URL_2)
.client(okHttpClient) // my question is here!!!
.build()
.create(MyService2.class);
}
What I want to know is...
Can I use one "OkHttpClient" on both services?
Is there any network issue?
or Should I make another OkHttpClient object like "okHttpClient2" and assign it to "myService2"?

java.net.SocketTimeoutException occurred after 1s~3s but my ok http timeout set 10s

My app is using Retrofit+okhttp.
Sometimes, it throw SocketTimeoutException just through
1s~3s after request but my okhttp timeout is setting 10s.
It's my code.
private static OkHttpClient getClient() {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.addInterceptor(headerinterceptor)
.build();
return client;
}
public static XXXX XXXX() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(XXXX)
.addConverterFactory(StatusProcessConverter.create(new GsonBuilder().setLenient().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(getClient())
.build();
XXXX methods = retrofit.create(XXXX.class);
return methods;
}
Can anyone help me ... why the sockettimeout occur less than 10s...

java.io.IOException when using Retrofit with rxandroid

I need to make HTTP DELETE request to my server with body provided.
I build the retrofit object in the following way:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.retryOnConnectionFailure(true)
.connectTimeout(2, TimeUnit.MINUTES)
.readTimeout(5, TimeUnit.MINUTES)
.writeTimeout(5, TimeUnit.MINUTES)
.build();
Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new GsonUTCDateAdapter())
.registerTypeAdapter(LocalDate.class, new GsonLocalDateAdapter())
.create();
return new Retrofit.Builder()
.baseUrl(AppConfig.API_BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
My Retrofit service method is:
#HTTP(method = "DELETE", path = "selfie/{publicId}/action/1", hasBody = true)
Observable<SimpleResponseModel> unlike(
#Path("publicId") String publicId,
#Body AuthorisedRequestModel model
);
I handle retrofit request/response in following way:
NetworkHelper
.getRetrofit()
.create(SelfieService.class)
.unlike(selfieModel.getPublicId(), new AuthorisedRequestModel())
.subscribeOn(Schedulers.io())
.subscribe(new CustomSubscriber<SimpleResponseModel>() {
#Override
public void onNext(SimpleResponseModel simpleResponseModel) {
ErrorHelper.handleServerError(simpleResponseModel);
}
});
I should mention, that all another requests GET,POST and PUT are working, but all DELETE requests are return me following error, from log:
HTTP FAILED: java.io.IOException: unexpected end of stream on okhttp3.Address#c6ec992c
So the request don't reach the server.
When I used Retrofit without rxandroid and made queries in AsyncTasks everything worked well.
Caused by:
Caused by: java.io.EOFException: \n not found: size=0 content=…
at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:215)
at okhttp3.internal.http.Http1xStream.readResponse(Http1xStream.java:186)
It is an issue. You can see it on GitHub:
https://github.com/square/okhttp/issues/1517

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;
}
}
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
try below code, it sét timeout is 20 seconds and readTimeout is 30 seconds
private OkHttpClient getRequestHeader() {
OkHttpClient httpClient = new OkHttpClient();
httpClient.setConnectTimeout(20, TimeUnit.SECONDS);
httpClient.setReadTimeout(30, TimeUnit.SECONDS);
return httpClient;
}
Then
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)
.client(getRequestHeader())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
I have used bellow like in Kotlin with MVVM Model..
var okHttpClient: OkHttpClient? = OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build()
private val api = Retrofit.Builder()
.baseUrl(baseurl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build()
.create(Api::class.java);
If you are using "com.squareup.retrofit2:retrofit:2.4.0" retrofit version > 2 then you try this one:
private OkHttpClient getRequestHeader()
{
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.build();
return okHttpClient;
}
In Kotlin you can Configure timeout for Retrofit by
Create OkHttpClient object with time in seconds (The default value is 10 seconds)
private val okHttpClient = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
Then use this object for Retrofit Builder
private val retrofit = Retrofit.Builder()
.addConverterFactory(ScalarsConverterFactory.create())
.client(okHttpClient)
.baseUrl(BASE_URL)
.build()
And import these
import java.util.concurrent.TimeUnit
import okhttp3.OkHttpClient
import retrofit2.Retrofit

Categories

Resources