且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查Java中是否存在Internet连接?

更新时间:2023-11-25 22:22:34

您应该连接到实际应用程序所需的位置。否则,您将测试您是否与某处无关(在这种情况下是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.