How to Find the Real URL Behind a Redirect in Java


Improve your writing skills in 5 minutes a day with the Daily Writing Tips email newsletter.

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.

2 thoughts on “How to Find the Real URL Behind a Redirect in Java

  1. Miss.Sunshine

    Nice one but why not
    String realURL = con.getHeaderField(“Location”).toString
    insted of
    String realURL = con.getHeaderField(3).toString
    ?

    Best regards

    Reply
    1. Daniel Scocco Post author

      You are correct, using (“Location”) is easier, as the position of this information might vary.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *