java urlconnection get the final redirected URL

Try this, I using recursively to using for many redirection URL.

public static String getFinalURL(String url) throws IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
    con.setInstanceFollowRedirects(false);
    con.connect();
    con.getInputStream();

    if (con.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM || con.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
        String redirectUrl = con.getHeaderField("Location");
        return getFinalURL(redirectUrl);
    }
    return url;
}

and using:

public static void main(String[] args) throws MalformedURLException, IOException {
    String fetchedUrl = getFinalURL("<your_url_here>");
    System.out.println("FetchedURL is:" + fetchedUrl);

}

Leave a Comment