使用 Java 检查互联网连接\
java programming java8object oriented programming更新于 2024/10/22 19:26:00
可以使用 java.net.URL 和 java.net.URLConnection 类检查互联网连接。以下是必需的步骤。
创建一个 URL 对象并将 URL 传递给它,例如 Google
调用 URL.openConnection() 方法获取 URLConnection 对象。
调用 URLConnection.connect() 方法检查互联网连接。如果尚未建立连接,则 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 已连接"); } catch (MalformedURLException e) { System.out.println("Internet 未连接"); } catch (IOException e) { System.out.println("Internet 未连接"); } } }
输出
Internet 已连接