Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 370
mindus Avatar asked Nov 03 '14 06:11

mindus


1 Answers

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.

like image 170
ilkayaktas Avatar answered Jan 29 '23 16:01

ilkayaktas