方法一
public static Boolean checkUrl(String address,int waitMilliSecond)
{
try{
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
conn.setConnectTimeout(waitMilliSecond);
conn.setReadTimeout(waitMilliSecond);
//HTTP connect
try {
conn.connect();
} catch(Exception e) {
e.printStackTrace();
return false;
}
int code = conn.getResponseCode();
if ((code >= 100) && (code < 400)){
return true;
}
return false;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
方法二
public static Boolean checkUrl2(String address,int timeout)
{
Socket socket = null;
try {
URL url = new URL(address);
String host = url.getHost();
int port = url.getPort();
if (port == -1) {
port = 80;
}
socket = new Socket();
InetSocketAddress isa = new InetSocketAddress(InetAddress.getByName(host), port);
socket.connect(isa, timeout);
if (socket.isConnected()) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
异步调用