如何检查Java中是否存在Internet连接? [英] How to check if internet connection is present in java?
问题描述
如何检查是否可以通过java连接到互联网?一种方法是:
How do you check if you can connect to the internet via java? One way would be:
final URL url = new URL("http://www.google.com");
final URLConnection conn = url.openConnection();
... if we got here, we should have net ...
如果您需要经常进行连续检查,并且互联网连接的丢失非常可能, 会更适合执行该任务
But is there something more appropriate to perform that task, especially if you need to do consecutive checks very often and a loss of internet connection is highly probable?
推荐答案
您应该连接到实际应用程序所需的位置。否则,您将测试您是否与某处无关(在这种情况下是Google)。
You should connect to the place that your actual application needs. Otherwise you're testing whether you have a connection to somewhere irrelevant (Google in this case).
特别是,如果您想与网络服务交谈,如果你是在web服务的控制,它是一个好主意,有某种廉价的获取状态的Web方法。这样,您就能更好地了解您的真实调用是否可能工作。
In particular, if you're trying to talk to a web service, and if you're in control of the web service, it would be a good idea to have some sort of cheap "get the status" web method. That way you have a much better idea of whether your "real" call is likely to work.
在其他情况下,只打开一个应该打开的端口连接可能足够 - 或发送ping。 InetAddress .isReachable
可能是适合您需要的API。
In other cases, just opening a connection to a port that should be open may be enough - or sending a ping. InetAddress.isReachable
may well be an appropriate API for your needs here.
这篇关于如何检查Java中是否存在Internet连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!