可能是重复问题:
如何在Java中检查是否存在Internet连接?
我希望能够找到一种简单的方法来检测在使用Java时是否存在Internet连接。目前的应用程序在Windows上使用WinInit DLL中的“InternetGetConnectedState”方法,但我的应用程序需要跨平台支持Mac操作系统,因此这种方法将不起作用。我也不会JNI来使用Java中的DLL,这让我感到非常沮丧。
我只能想到两种方法:尝试打开与网站的URL连接,如果失败,则返回false;另外一种方法在下面,但我不知道它是否普遍稳定。当我拔掉网络电缆时,创建InetAddress时我会得到UnknownHostException。否则,如果电缆已连接,则可以获得有效的InetAddress对象。我还没有在Mac上测试下面的代码。
感谢您提供的任何示例或建议。
更新:最终代码块位于底部。我决定采纳HTTP请求(在这种情况下是Google)的建议。它很简单,发送一个请求以返回数据。如果无法从连接获取任何内容,则没有互联网连接。
public static boolean isInternetReachable()
{
try {
InetAddress address = InetAddress.getByName("java.sun.com");
if(address == null)
{
return false;
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
最终代码块://checks for connection to the internet through dummy request
public static boolean isInternetReachable()
{
try {
//make a URL to a known source
URL url = new URL("http://www.google.com");
//open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
//trying to retrieve data from the source. If there
//is no connection, this line will fail
Object objData = urlConnect.getContent();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}