package com.reflect;java
/* 第一種 */
import java.io.InputStream;
import java.net.URL;
/**
*@author WHD
*2014-10-21
*/
public class Urlcon {
public static void main(String[] args) {
URL url;
try {
url = new URL("http://www.baidu.com/");
InputStream in = url.openStream();
System.out.println("鏈接可用");
} catch (Exception e1) {
System.out.println("鏈接打不開!");
url = null;
}
}
}網絡
/* 第二種 */url
/**
*
*/
package com.reflect;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 文件名稱爲:URLAvailability.java
* 文件功能簡述: 描述一個URL地址是否有效
* @author Jason
* @time 2010-9-14
*
*/
public class URLAvailability {
private static URL url;
private static HttpURLConnection con;
private static int state = -1;
/**
* 功能:檢測當前URL是否可鏈接或是否有效,
* 描述:最多鏈接網絡 5 次, 若是 5 次都不成功,視爲該地址不可用
* @param urlStr 指定URL網絡地址
* @return URL
*/
public synchronized URL isConnect(String urlStr) {
int counts = 0;
if (urlStr == null || urlStr.length() <= 0) {
return null;
}
while (counts < 5) {
try {
url = new URL(urlStr);
con = (HttpURLConnection) url.openConnection();
state = con.getResponseCode();
System.out.println(counts +"= "+state);
if (state == 200) {
System.out.println("URL可用!");
}
break;
}catch (Exception ex) {
counts++;
System.out.println("URL不可用,鏈接第 "+counts+" 次");
urlStr = null;
continue;
}
}
return url;
}
public static void main(String[] args) {
URLAvailability u=new URLAvailability();
u.isConnect("http://www.baidu.com");
}
}
.net