The code snippet presented below shows how to check if a web page exists not not.
public class URLUtils {
public static void main(String s[]) {
System.out.println(URLUtils.exists
("http://www.java-forums.org/howto.html"));
System.out.println(URLUtils.exists
("http://www.java-forums.org/pagenotfound.html"));
/*
output :
true
false
*/
}
public static boolean exists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =
(HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
}