java.net.SocketTimeoutException: timeout
Solution 1:
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
Solution 2:
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();
Solution 3:
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();
Solution 4:
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()
Solution 5:
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,
- HttpException
- SocketTimeoutException
- FATAL EXCEPTION: DefaultDispatcher etc
Here is my usersList()
function
@GET(AppConstants.APIEndPoints.HOME_CONTENT)
suspend fun usersList(): UserListResponseModel