|
The exmaple below shows a way to check whether a web page exists or not.
import java.net.*;
import java.io.*;
public class Check {
public static void main(String s[]) {
System.out.println(exists("http://www.java-tips.org/home/"));
System.out.println(exists("http://www.java-tips.org/homeless/"));
}
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;
}
}
}
|
The following is doing the same thing but this time we identify ourself to a proxy.
import java.net.*;
import java.io.*;
import java.net.*;
import java.util.Properties;
public class CheckUrl {
public static void main(String s[]) {
new CheckUrl().doit();
}
public void doit() {
System.out.println(exists("http://www.rgagnon.com"));
System.out.println(exists("http://www.yahoo.com"));
}
public boolean exists(String URLName){
try {
Properties systemSettings = System.getProperties();
systemSettings.put("proxySet", "true");
systemSettings.put("http.proxyHost","proxy.mycompany.local") ;
systemSettings.put("http.proxyPort", "80") ;
URL u = new URL(URLName);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
String encodedUserPwd =
encoder.encode("domain\\username:password".getBytes());
con.setRequestProperty
("Proxy-Authorization", "Basic " + encodedUserPwd);
con.setRequestMethod("HEAD");
System.out.println
(con.getResponseCode() + " : " + con.getResponseMessage());
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
|
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.