I use HttpURLConnection to check if the server url is accessible 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 works fine under normal conditions. But when there is no Internet connection (since either the router is disconnected or there is no access point), httpConnection.getResponseCode() fails (the function does not return). How can i fix this?
source share