Thursday, September 3, 2009

Programatically determining redirected URL

In order to detect the redirect, you have to use setFollowRedirects(false). Otherwise, you end up on the redirected page anyway with a responseCode of 200. However you will have to navigate the redirected url yourself.

using java.net.HttpURLConnection

URL url = new URL(urlstring);
// Determine if the url has redirected
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
if(uc.getResponseCode() == 300 uc.getResponseCode() == 302)
{
String newUrl = uc.getHeaderField("Location");

}