How to handle HTTP timeout?

22,518

Solution 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);
    }

Solution 2

Increase your time of waiting for response like :

HttpConnectionParams.setConnectionTimeout( httpParameters, 60000 ); //1 minute
HttpConnectionParams.setSoTimeout( httpParameters, 90000 ); // 1.5 minute
Share:
22,518
Louis Evans
Author by

Louis Evans

Updated on August 06, 2020

Comments

  • Louis Evans
    Louis Evans over 3 years

    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?

    • user370305
      user370305 over 10 years
      Simple put try-catch block and catch the TimeOut.
    • Boris Mocialov
      Boris Mocialov over 10 years
      The connection timeout throws "java.net.SocketTimeoutException: Socket is not connected" and the socket timeout "java.net.SocketTimeoutException: The operation timed out". so try catch
    • Hossam Oukli
      Hossam Oukli over 10 years
      You need to accept VM's Answer it was his idea.
  • VM4
    VM4 over 10 years
    That's because SocketTimeoutException is a SubType of IOException. :)
  • VM4
    VM4 over 10 years
    Corrected it to catch both.
  • Amit
    Amit almost 3 years
    gotta catch'em all