How to handle HTTP timeout?-Collection of common programming errors

In my application, I am downloading JSON data from a ReST web service. Most of the time, this works fine, however sometimes the connection will time out.

This is the code I use to set the timeout…

HttpConnectionParams.setConnectionTimeout( httpParameters, 20000 );
HttpConnectionParams.setSoTimeout( httpParameters, 42000 );

If the connection times out, the application crashes and closes, how do I handle a time out?

  1. The HttpClient class throws a ConnectTimeoutException Exception, so you should listen for it:

    try {
            HttpResponse response = client.execute(post);
                        // do something with response
        } catch (ConnectTimeoutException e) {
            Log.e(TAG, "Timeout", e);
        } catch (SocketTimeoutException e) {
            Log.e(TAG, " Socket timeout", e);
        }
    
  2. Increase your time of waiting for response like :

    HttpConnectionParams.setConnectionTimeout( httpParameters, 60000 ); //1 minute
    HttpConnectionParams.setSoTimeout( httpParameters, 90000 ); // 1.5 minute
    
  3. I have tried to catch a variety of exception types, I have found that catching an IOException worked as I wanted!