可以使用java.net.URL和java.net.URLConnection类检查Internet连接。以下是必需的步骤。
创建一个URL对象并将URL传递给它,说Google
调用URL.openConnection()方法以获取URLConnection对象。
调用URLConnection.connect()方法检查Internet连接。connect()
如果尚未建立连接,则该方法将打开指向所传递URL所引用资源的通信链接。
import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class Tester { public static void main(String[] args) { try { URL url = new URL("http://www.google.com"); URLConnection connection = url.openConnection(); connection.connect(); System.out.println("Internet is connected"); } catch (MalformedURLException e) { System.out.println("Internet is not connected"); } catch (IOException e) { System.out.println("Internet is not connected"); } } }
输出结果
Internet is connected