Sorry if this question has been answered before, I just don't seem to get the solution to the problem I am facing.
I have a method that checks if there is an internet connection and returns true if the host computer is connected to the internet; false if not.
Here is the method
public static boolean isConnectedToInternet() {
try {
URL url = new URL("https://www.google.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.connect();
if (con.getResponseCode() == 200) {
return true;
} else return false;
} catch (Exception e) {
return false;
}
}
This code works well and it is able to give the right response except it sometimes takes too long. For example, if my internet connection is very slow it can take as long as 3 or even 5 minutes. That is too long!
I need to find a way to implement a timeout so that if the response takes more than 2000 milliseconds, attempt to connect to google.com
is stopped and the host is assumed not to be connected to the internet.
How can I implement this?