java检测一个地址是不是能访问的地址
/**
* 功能:检测当前URL是否可连接或是否有效,
* @param urlStr 指定URL网络地址
* @param timeOutMillSeconds 超时时间,默认不设置(为0时就是不设置)
* @param reconnectTime 重连次数,默认为一次
* @return URL
*/
public static boolean isConnect(String urlStr, int timeOutMillSeconds, int reconnectTime) {
int counts = 0;
if (urlStr == null || urlStr.length() <= 0) {
return false;
}
if (reconnectTime <= 1) {
reconnectTime = 1;
}
while (counts < reconnectTime) {
System.out.println("链接次数:"+(counts+1));
try {
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (timeOutMillSeconds != 0 && timeOutMillSeconds > 0) {
con.setConnectTimeout(timeOutMillSeconds);
}
int state = con.getResponseCode();
if (state == 200) {
return true;
}
counts ++;
continue;
} catch (Exception ex) {
counts ++;
continue;
}
}
return false;
}