Getting java.net.SocketTimeoutException: Connection timed out in android
I've searched all over the web and after reading lot of docs regarding connection timeout exception, the thing I understood is that, preventing SocketTimeoutException
is beyond our limit. One way to effectively handle it is to define a connection timeout and later handle it by using a try-catch
block. Hope this will help anyone in future who are facing the same issue.
HttpUrlConnection conn = (HttpURLConnection) url.openConnection();//set the timeout in millisecondsconn.setConnectTimeout(7000);
I'm aware this question is a bit old. But since I stumbled on this while doing research, I thought a little addition might be helpful.
As stated the error cannot be solved by the client, since it is a network related issue. However, what you can do is retry connecting a few times. This may work as a workaround until the real issue is fixed.
for (int retries = 0; retries < 3; retries++) { try { final HttpClient client = createHttpClientWithDefaultSocketFactory(null, null); final HttpResponse response = client.execute(get); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { throw new IllegalStateException("GET Request on '" + get.getURI().toString() + "' resulted in " + statusCode); } else { return response.getEntity(); } } catch (final java.net.SocketTimeoutException e) { // connection timed out...let's try again }}
Maybe this helps someone.
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
Note: Your RetrofitClient Classs must have this as client
OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS)