首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

测试URL是不是可用

2012-09-20 
测试URL是否可用import java.net.URL?? import java.net.HttpURLConnection?? ? public class test2 {??

测试URL是否可用

import java.net.URL;??
import java.net.HttpURLConnection;??
?
public class test2 {??
??? private boolean isConnect(String url) {??
??????? boolean flag = false;??
??????? int counts = 0;??
??????? if (url == null || url.length() <= 0) {??
??????????? return flag;??
??????? }??

??????? //测试5次
??????? while (counts < 5) {??
??????????? try {??
??????????????? HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();??
??????????????? int state = connection.getResponseCode();??
??????????????? if (state == 200) {? //200:可用,401不可用
??????????????????? flag = true;??
??????????????? }??
??????????????? break;??
??????????? } catch (Exception ex) {??
??????????????? counts++;??
??????????????? continue;??
??????????? }??
??????? }??
??????? return flag;??
??? }??
?
??? public static void main(String[] args) {??
??? ??? test2 check = new test2();??
??? ??? System.out.println(check.isConnect("http://www.baidu.com/"));??
??? }??
}?

热点排行