简体   繁体   中英

How to check internet connection using java

I have a small project which needs internet connection. Unfortunately my internet is occasionally down. Then it throws away exception:

"java.net.SocketException: Network is unreachable"

...

My idea was to check internet connection before I do any operation and if it's down, just wait a few seconds and try again and again until its not working. But it throws same exception.

My code:

        URL url = new URL("https://www.google.com");
        URLConnection conn = url.openConnection();


        InetAddress check = InetAddress.getByName("www.google.com");

        while (check.isReachable(3000)) {
            wait(5000);
        }

This might be what you're looking for. If an exception is thrown or isReachable is false the loop will keep checking but as soon as it is isReachable is true the loop will exit.

    URL url = new URL("https://www.google.com");
    URLConnection conn = url.openConnection();

    InetAddress check = InetAddress.getByName("www.google.com");

        while (true) {
            try {
                boolean isReachable = check.isReachable(3000);
                if (isReachable) {
                    break;
                }
            } catch (Exception e) {
                wait(5000);
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM