简体   繁体   中英

Java checking internet connection on Linux issue

I need to check internet connection, so I write this small class:

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

public class TestConnection {
    public boolean isInternetAccessed() {
        try {
            URL url = new URL("http://www.google.com");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(4000);
            con.connect();

            if (con.getResponseCode() == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception exception) {
            System.out.println("No Connection");
            return false;
        } 
    }
    public static void main(String[] args) {
        Timer timer = new Timer();
        int period = 10000;
        timer.scheduleAtFixedRate(new TimerTask() {
            TestConnection internetCheck = new TestConnection();

            public void run() {
                try {
                    System.out.println("Starting..................");
                    System.out.println("Internet Status: " + internetCheck.isInternetAccessed());
                    System.out.println("Sleeping..................");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }, 0, period);
    }

}

This program running fine in Java 1.7 on Window machine. But in Linux, it have problem: If I disconnect this machine from internet, and run this program, after that I connect this machine to Internet, and the program always said cannot connect.

Any help?

The Programs works correctly in Linux Environment too. Please check your environment issue if there is any. No problem with the code

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