7

I am using a HttpURLConnection to check whether the server URL is available or not by using the following code:

try {
    boolean connectionFailed = false;
    URL knownURL = new URL("http://www.google.com");
    httpConnection = (HttpURLConnection) knownURL.openConnection();
    httpConnection.setConnectTimeout(5000);
    responseCode = httpConnection.getResponseCode();
    if (responseCode != 200)  {
        status = ConnectionStatus.NOT_CONNECTED; 
    }
}
catch(Exception e) {
    connctionFailed = true;
}

This code is working fine under normal conditions. But when there is no Internet connection (because either the router is disconnected or not the hotspot), httpConnection.getResponseCode() is not executed (the function does not return). How can I fix this?

honk
  • 9,137
  • 11
  • 75
  • 83
mindus
  • 171
  • 2
  • 10
  • Try to put code snippet in `TRY CATCH Block`. What i suspect is `(HttpURLConnection) knownURL.openConnection();` throws a socket exception when there is no internet, so you're not reaching to ` httpConnection.getResponseCode();` – Nitin Misra Nov 03 '14 at 06:54
  • knownURL.openConnection() is executing and it's not coming to catch block. It's stop on when calling getResponseCode() – mindus Nov 03 '14 at 07:03
  • try debugging it. And yes, you are getting an exception. That's why. Check your logcat and post here maybe. – Darpan Nov 03 '14 at 07:20
  • HttpUrlConnection works without internet? – Amir Nov 04 '14 at 05:20

2 Answers2

6

httpConnection.setConnectTimeout(5000) is a timeout for connection.

This is not a timeout for httpConnection.getResponseCode().

If you add httpConnection.setReadTimeout(2000), httpConnection.getResponseCode()should throw an exception when no connection is available.

ilkayaktas
  • 188
  • 1
  • 7
  • This seems as it should be causing the getResponseCode() to start throwing TimeOutExceptions. Did it? I have similar problem and am looking for the simple solution, without having to program the timeouts myself. – Luka Bradeško Aug 18 '15 at 11:03
0

You may be having a try catch block at higher layer which is catching the sockettimeout exception.

Aun
  • 1,883
  • 1
  • 17
  • 26