Wednesday, September 12, 2007

Java Program to detect Server side redirections!

As a part of my research work, I wrote this small function in Java which gives you HTTP Response Code and with which we can actually detect server side redirects. The server side redirects have a response code as 302. Well here is the program,

public class NetworkTool {
public static int getResponseCode(String url) {

try {
URL urlItem = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlItem.openConnection();
con.setReadTimeout(1000);
con.setConnectTimeout(5000);
//System.out.println(con.getConnectTimeout());
con.setInstanceFollowRedirects(false);
int res = con.getResponseCode();
return res;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
catch(Exception ex){//System.out.println("hehe");
}
return -1;
}

public static void main(String[] args)
{
System.out.println(getResponseCode("http://cs.uga.edu/index.htmx"));
System.out.println(getResponseCode("http://buddibuddibuddi.com"));
System.out.println(getResponseCode("http://128.192.1.21"));
}
}

The statements highlighted in bold are important. Otherwise, there are some url for which you get connected to the server but you keep waiting for infinite time for the data to come on the connection. So if we set time-out on read, we don't wait for long and this is especially helpful when you run the tests on huge data.
It took me quite a long time to get the actual code fixed, and then to find out the two statements. So I hope this post would be useful for others too.

No comments: