JAVA验证URL是否有效连接的方法

来源:互联网 发布:闪字风扇软件下载 编辑:程序博客网 时间:2024/06/04 18:09

昨天做了个监控远程服务器是否正常连接,费了很大脑动力,写成了下面的方法,现在分享给大家,希望可以帮助都更多的人。

写个方法的时候一直有个误区,不知道怎么去监控远程服务器,望遇到同样问题人,跳出这个思想禁区,试着想想,监控远程应用。

下面这个例子就是连接百度应用做的小例子。连接上就会返回true,否则返回false.

public class UrlTest {

private boolean isConnection(String url) {
boolean flag = false;
int counts = 0;
if (null == url || url.length() <= 0) {
return flag;
}
while (counts < 10) {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url)
.openConnection();
int state = connection.getResponseCode();
if (state == 200) {
flag = true;
}
break;
} catch (Exception e) {
counts++;
continue;
}
}
return flag;
}


public static void main(String[] args) {
UrlTest test1 = new UrlTest();
System.out.println(test1.isConnection("http://www.baidu.comfgdhdf"));
}
0 0