在 Java 中检查互联网连接\n
可以使用 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 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP