package com.test;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
public class SampleforTestURL {
public static void main(String s[]) {
System.out.println(exists("http://www.google.com.tw"));
System.out.println(exists("http://www.yahoo.com.tw"));
System.out.println(exists("http://www.yam.com.tw"));
}
static boolean exists(String URLName) {
try {
HttpURLConnection.setFollowRedirects(true);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con = (HttpURLConnection) new URL(URLName)
.openConnection();
con.setConnectTimeout(5000); // set timeout to 5 seconds
con.setReadTimeout(5000); // set read timeout to 5 seconds
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (SocketTimeoutException e) {
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
2014年5月25日 星期日
[JAVA]判斷網址是否可用 使用HttpURLConnection
直接看程式碼:
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言