如何检查Java中是否存在Internet连接?
-
05-07-2019 - |
题
如何检查是否可以通过java连接到互联网?一种方法是:
final URL url = new URL("http://www.google.com");
final URLConnection conn = url.openConnection();
... if we got here, we should have net ...
但是,如果您需要经常进行连续检查并且极有可能丢失互联网连接,那么执行该任务是否更合适?尤其?
解决方案
您应该连接到实际应用程序所需的位置。否则,您正在测试您是否与某个无关的地方有联系(在这种情况下为Google)。
特别是,如果您正在尝试与Web服务进行通信,并且如果您正在控制Web服务,那么获得某种便宜的“获取状态”将是一个好主意。网络方法。通过这种方式,您可以更好地了解您的“真实”情况。电话很可能有用。
在其他情况下,只打开一个应该打开的端口的连接就足够了 - 或者发送ping。 InetAddress.isReachable 代码>
可能是适合您需求的API。
其他提示
您基本提供的代码,以及对 connect
的调用应该足够了。所以,是的,可能只是谷歌不可用,但你需要联系的其他网站,但有多大可能?此外,此代码只应在您实际无法访问外部资源时执行(在 catch
块中尝试找出失败的原因是什么)所以我会说如果您同时感兴趣的外部资源和 Google没有机会您遇到网络连接问题。
private static boolean netIsAvailable() {
try {
final URL url = new URL("http://www.google.com");
final URLConnection conn = url.openConnection();
conn.connect();
conn.getInputStream().close();
return true;
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
return false;
}
}
人们建议使用INetAddress.isReachable。问题是某些站点配置其防火墙以阻止ICMP Ping消息。所以“ping”即使Web服务可访问,也可能会失败。
当然,反过来也是如此。即使Web服务器已关闭,主机也可能会响应ping。
当然,由于本地防火墙限制,计算机可能无法直接连接到某些(或所有)Web服务器。
根本问题是“可以连接到互联网”。是一个定义不明确的问题,如果没有这个问题很难测试:
- 关于用户机器和“本地”机器的信息。网络环境,
- 有关应用需要访问的信息。 醇>
一般来说,最简单的解决方案是让应用程序只是尝试访问它需要访问的内容,并依靠人工智能进行诊断。
如果您使用的是java 6,可以使用 NetworkInterface 检查可用的网络接口。 即像这样的东西:
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface interf = interfaces.nextElement();
if (interf.isUp() && !interf.isLoopback())
return true;
}
尚未自己尝试过。
此代码:
"127.0.0.1".equals(InetAddress.getLocalHost().getHostAddress().toString());
返回 - 对我来说 - 如果离线则为 true
,否则为 false
。 (好吧,我不知道这对所有电脑都是如此)。
这比其他方法更快,在这里。
编辑:我发现只有“翻转开关”才能正常工作。 (在笔记本电脑上)或其他系统定义的选项,用于互联网连接,已关闭。也就是说,系统本身知道不会寻找任何IP地址。
此代码可以可靠地完成工作。
请注意,使用 try-with-resources <时/ code>
声明我们不需要关闭资源。
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class InternetAvailabilityChecker
{
public static boolean isInternetAvailable() throws IOException
{
return isHostAvailable("google.com") || isHostAvailable("amazon.com")
|| isHostAvailable("facebook.com")|| isHostAvailable("apple.com");
}
private static boolean isHostAvailable(String hostName) throws IOException
{
try(Socket socket = new Socket())
{
int port = 80;
InetSocketAddress socketAddress = new InetSocketAddress(hostName, port);
socket.connect(socketAddress, 3000);
return true;
}
catch(UnknownHostException unknownHost)
{
return false;
}
}
}
我通常将其分解为三个步骤。
- 我首先看到我是否可以将域名解析为IP地址。
- 然后我尝试通过TCP连接(端口80和/或443)并正常关闭。
- 最后,我将发出HTTP请求并检查200响应。 醇>
如果它在任何时候都失败,我会向用户提供相应的错误消息。
URL url=new URL("http://[any domain]");
URLConnection con=url.openConnection();
/*now errors WILL arise here, i hav tried myself and it always shows "connected" so we'll open an InputStream on the connection, this way we know for sure that we're connected to d internet */
/* Get input stream */
con.getInputStream();
将上述语句放在try catch块中,如果catch中的异常意味着没有建立Internet连接。 : - )
使用NetworkInterface等待网络为我工作的代码,直到我从固定网络地址切换到DHCP。稍微增强使其也适用于DHCP:
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface interf = interfaces.nextElement();
if (interf.isUp() && !interf.isLoopback()) {
List<InterfaceAddress> adrs = interf.getInterfaceAddresses();
for (Iterator<InterfaceAddress> iter = adrs.iterator(); iter.hasNext();) {
InterfaceAddress adr = iter.next();
InetAddress inadr = adr.getAddress();
if (inadr instanceof Inet4Address) return true;
}
}
}
适用于IPv4网络的openSuse 13.1中的Java 7。原始代码的问题在于,虽然从挂起恢复后接口已启动,但尚未分配IPv4网络地址。等待此分配后,程序可以连接到服务器。但我不知道在IPv6的情况下该怎么做。
InetAddress.isReachable
如果存在互联网连接,有时会返回false。
检查java中的Internet可用性的另一种方法是:此函数生成一个真正的 ICMP ECHO
ping。
public static boolean isReachableByPing(String host) {
try{
String cmd = "";
if(System.getProperty("os.name").startsWith("Windows")) {
// For Windows
cmd = "ping -n 1 " + host;
} else {
// For Linux and OSX
cmd = "ping -c 1 " + host;
}
Process myProcess = Runtime.getRuntime().exec(cmd);
myProcess.waitFor();
if(myProcess.exitValue() == 0) {
return true;
} else {
return false;
}
} catch( Exception e ) {
e.printStackTrace();
return false;
}
}
1)找出应用程序需要连接的位置。
2)设置工作进程以检查 InetAddress.isReachable 以监控与该地址的连接。
此代码包含在我用于测试连接是否可用的jUnit测试类中。我总是收到一个连接,但如果你检查内容长度,如果不知道它应该是-1:
try {
URL url = new URL("http://www.google.com");
URLConnection connection = url.openConnection();
if(connection.getContentLength() == -1){
fail("Failed to verify connection");
}
}
catch (IOException e) {
fail("Failed to open a connection");
e.printStackTrace();
}
public boolean checkInternetConnection()
{
boolean status = false;
Socket sock = new Socket();
InetSocketAddress address = new InetSocketAddress("www.google.com", 80);
try
{
sock.connect(address, 3000);
if(sock.isConnected()) status = true;
}
catch(Exception e)
{
status = false;
}
finally
{
try
{
sock.close();
}
catch(Exception e){}
}
return status;
}
还有一个gradle选项 - offline
,这可能会导致你想要的行为。
以下代码允许我们在Android设备上获取网络状态
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView mtv=findViewById(R.id.textv);
ConnectivityManager connectivityManager=
(ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(((Network)connectivityManager.getActiveNetwork())!=null)
mtv.setText("true");
else
mtv.setText("fasle");
}
}
}