如何使用Java测试互联网的可用性? [英] How do I test the availability of the internet in Java?

查看:42
本文介绍了如何使用Java测试互联网的可用性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从url.openStream()捕获异常时,我不想告诉您互联网不可用的困难方式.

I don't want to tell the hard way that the internet is unavailable when I catch an exception from url.openStream().

是否有一种简单的方法可以判断计算机是否已使用Java连接到互联网?在这种情况下,连接到Internet"意味着能够从特定的URL下载数据.

Is there a simple way to tell if the computer is connected to the internet in Java? In this scenario, "connected to the internet" means being able to download data from a specific url.

如果我尝试从中下载但无法下载,则该程序挂起了一段时间.我不想挂.因此,我需要一种快速的方法来查询该网站是否可用.

If I try to download from it and it is not available, then the program hangs for a bit. I dont want that hanging. Therefore, i need a fast way of querying whether the website is available or not.

推荐答案

您要避免的问题是等待HTTP连接确定您要访问的URL确实不可用.为了实现这一点,您需要停止使用url.openStream()(这是openConnection().getInputStream()的快捷方式),并更好地控制您的连接.

The problem you are trying to avoid is waiting for for your http connection to determine that the URL you are trying to access is really unavailable. In order to achieve this you need to stop using url.openStream() which is a shortcut for openConnection().getInputStream() and get some finer control over your connection.

URLConnection conn = url.openConnection();  
conn.setConnectTimeout(timeoutMs);  
conn.setReadTimeout(timeoutMs);  
in = conn.getInputStream();  

如果连接或读取超出您在timeoutMs参数中提供的时间,则此代码将允许您使连接尝试超时.

This code will allow you to timeout the connection attempt if either the connection or the read exceeds the time you provide in the timeoutMs paramater.

这篇关于如何使用Java测试互联网的可用性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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