How to Find the Real URL Behind a Redirect in Java

Say you have a URL that redirects to another (e.g., How do you find the real URL behind the redirect?

You can do this in Java using the HttpURLConnection class. Like this:

String url = "";
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
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

    1. Daniel Scocco Post author

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


Leave a Reply

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