Here you can find the source of getRedirectedUrl(String url)
public static String getRedirectedUrl(String url) throws MalformedURLException, IOException
//package com.java2s; //License from project: LGPL import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class Main { public static String getRedirectedUrl(String url) throws MalformedURLException, IOException { HttpURLConnection connection; String finalUrl = url;//from w w w . ja va2 s . co m 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 (redirectedUrl == null) break; finalUrl = redirectedUrl; } else break; } while (connection.getResponseCode() != HttpURLConnection.HTTP_OK); connection.disconnect(); return finalUrl.replaceAll(" ", "%20"); } }