如何检查Java中是否存在互联网连接? [英] How to check if internet connection is present in Java?

查看:53
本文介绍了如何检查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).

特别是,如果您正在尝试与网络服务对话,并且您可以控制网络服务,那么使用某种廉价的获取状态"网络方法将是一个好主意.这样您就可以更好地了解您的真实"通话是否可行.

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中是否存在互联网连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆