Getting Connection timed out in android

Getting Connection timed out in android

Getting Connection timed out in android

Ive 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 milliseconds

Im 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 e) {
        // connection timed out...lets try again                

Maybe this helps someone.

Getting Connection timed out in android

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()
        } catch (e: Exception) {

Where, Exception is type of kotlin and not of java.lang

This will handle every exception like,

  1. HttpException
  2. SocketTimeoutException
  3. FATAL EXCEPTION: DefaultDispatcher etc

Here is my usersList() function

suspend fun usersList(): UserListResponseModel

Your RetrofitClient Classs must have this as client

            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)

Related posts on Android :

Leave a Reply

Your email address will not be published.