Skip to content

Instantly share code, notes, and snippets.

@zalizko
Created June 1, 2020 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zalizko/cb4b43c6810b18947bf9f68d9691db6e to your computer and use it in GitHub Desktop.
Save zalizko/cb4b43c6810b18947bf9f68d9691db6e to your computer and use it in GitHub Desktop.
Testing internet connection
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class TestInternet {
public static void main(String[] args) throws Exception {
new TestInternet().run();
}
private void run() throws Exception {
String[] urls = new String[]{
"https://www.google.com",
"http://www.google.com"
};
for (String url : urls) {
synchronized (TestInternet.class) {
if (isReachable(url)) {
System.out.printf("%s OK\n", getTime());
} else {
System.out.printf("%s NOK\n", getTime());
}
}
}
}
public boolean isReachable(String url) {
HttpURLConnection connection = null;
try {
System.out.printf("%s connecting %s ...\n", getTime(), url);
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout((int) Duration.ofSeconds(2).toMillis());
connection.setReadTimeout((int) Duration.ofSeconds(3).toMillis());
System.out.println(connection.getPermission());
Object objData = connection.getContent();
} catch (Exception e) {
System.out.printf("%s ERROR: %s\n", getTime(), e.getMessage());
return false;
} finally {
if (connection != null) {
connection.disconnect();
}
}
return true;
}
private String getTime() {
return LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment