Say you have a URL that redirects to another (e.g., bit.ly). How do you find the real URL behind the redirect?
You can do this in Java using the HttpURLConnection class. Like this:
String url = "http://bit.ly/23414";
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setInstanceFollowRedirects(false);
con.connect();
String realURL = con.getHeaderField(3).toString();
You basically create a connection, disable auto-follow of the redirect, connect, and then query the header information to see where the redirect was pointing.
Nice one but why not
String realURL = con.getHeaderField(“Location”).toString
insted of
String realURL = con.getHeaderField(3).toString
?
Best regards
You are correct, using (“Location”) is easier, as the position of this information might vary.