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?
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