With OkHttp
library, application is facing following SocketTimeoutException
issue. If request size is less, then it is working fine(Less than 1MB). I a
this resolved my problem:
OkHttpClient innerClient = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.MINUTES) // connect timeout
.writeTimeout(5, TimeUnit.MINUTES) // write timeout
.readTimeout(5, TimeUnit.MINUTES) // read timeout
.build();
For OkHttp 3 the default value for OkHttp is 10 seconds. You can increase the timeout to 30 seconds.
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(30, TimeUnit.SECONDS); // connect timeout
client.setReadTimeout(30, TimeUnit.SECONDS); // socket timeout
Use this for Kotlin
val client1 = OkHttpClient.Builder()
.connectTimeout(2, TimeUnit.MINUTES)
.writeTimeout(2, TimeUnit.MINUTES) // write timeout
.readTimeout(2, TimeUnit.MINUTES) // read timeout
.addInterceptor(
BasicAuthInterceptor(
AmvaccAppConstants.AUTHENTICATE_USER_NAME, AmvaccAppConstants.AUTHENTICATE_USER_PASSWORD
)
)
.addInterceptor(interceptor)
.build()
I solved that problem increasing writeTimeout()
.
Try:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(5, TimeUnit.MINUTES) // connect timeout
.writeTimeout(5, TimeUnit.MINUTES) // write timeout
.readTimeout(5, TimeUnit.MINUTES); // read timeout
okHttpClient = builder.build();
If you are using Retrofit and Kotlin then use following code:
var BASE_URL:String="Your URL"
val clientSetup = OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.MINUTES)
.writeTimeout(1, TimeUnit.MINUTES) // write timeout
.readTimeout(1, TimeUnit.MINUTES) // read timeout
.build()
val getClientApi: ApiInterface
get() {
var retrofit: Retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(clientSetup)
.build()
}
You need to understand that only adding this won't solve your problem:
OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
If you are using Kotlin + Retrofit + Coroutines then just use try
and catch
for network operations like,
viewModelScope.launch(Dispatchers.IO) {
try {
val userListResponseModel = apiEndPointsInterface.usersList()
returnusersList(userListResponseModel)
} catch (e: Exception) {
e.printStackTrace()
}
}
Where, Exception is type of kotlin
and not of java.lang
This will handle every exception like,
Here is my usersList()
function
@GET(AppConstants.APIEndPoints.HOME_CONTENT)
suspend fun usersList(): UserListResponseModel