java urlconnection get the final redirected URL

Solution 1:

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);

}

Solution 2:

public static String getFinalRedirectedUrl(String url) {

    HttpURLConnection connection;
    String finalUrl = url;
    try {
        do {
            connection = (HttpURLConnection) new URL(finalUrl)
                    .openConnection();
            connection.setInstanceFollowRedirects(false);
            connection.setUseCaches(false);
            connection.setRequestMethod("GET");
            connection.connect();
            int responseCode = connection.getResponseCode();
            if (responseCode >= 300 && responseCode < 400) {
                String redirectedUrl = connection.getHeaderField("Location");
                if (null == redirectedUrl)
                    break;
                finalUrl = redirectedUrl;
                System.out.println("redirected url: " + finalUrl);
            } else
                break;
        } while (connection.getResponseCode() != HttpURLConnection.HTTP_OK);
        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return finalUrl;
}

Solution 3:

My first idea would be setting instanceFollowRedirects to false, or using URLConnection instead.

In both cases, the redirect won't be executed, so you will receive a reply to your original request. Get the HTTP Status value and, if it is 3xx, get the new redirect value.

Of course there may be a chain of redirects, so probably you will want to iterate until you reach the real (status 2xx) page.