HttpURLConnection getResponseCode() deos not return if there is no Internet connection
Asked Answered
H

2

8

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?

Homogamy answered 3/11, 2014 at 6:43 Comment(4)
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();`Goodbye
knownURL.openConnection() is executing and it's not coming to catch block. It's stop on when calling getResponseCode()Homogamy
try debugging it. And yes, you are getting an exception. That's why. Check your logcat and post here maybe.Jackquelin
HttpUrlConnection works without internet?Attaboy
O
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.

Obtain answered 12/2, 2015 at 9:11 Comment(2)
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.Disorientate
It could also be the DNS look that's failing, and that doesn't have a timeout the user can specify. It also throws a different type of exception which you might not catch, depending on how you're catching the exceptions.Mechelle
P
0

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

Perch answered 3/11, 2014 at 7:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.