java.net.SocketTimeoutException in okhttp
IOExceptiojava.net.SocketTimeoutExceptionis occurring on following condition.
- Server is slow and default timeout is less. so just put timeout value according to you.
- Server is working fine but timeout value is for less time. so change the timeout value. like below code snippet.
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(30, TimeUnit.SECONDS);client.setReadTimeout(30, TimeUnit.SECONDS);client.setWriteTimeout(30, TimeUnit.SECONDS);
If you are using okhttp3 then you must do it using the builder.
OkHttpClient.Builder builder = new OkHttpClient.Builder();builder.connectTimeout(30, TimeUnit.SECONDS); builder.readTimeout(30, TimeUnit.SECONDS); builder.writeTimeout(30, TimeUnit.SECONDS); client = builder.build();
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