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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With