java檢測一個地址是否是能訪問的地址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;
}網絡