java urlconnection get the final redirected URL

2020-01-27 07:28发布

I have a url which redirects to another url.I want to be able to get the final redirected URL.My code:

    public class testURLConnection
    {
    public static void main(String[] args) throws MalformedURLException, IOException {

    HttpURLConnection con =(HttpURLConnection) new URL( "http://tinyurl.com/KindleWireless" ).openConnection();

    System.out.println( "orignal url: " + con.getURL() );
    con.connect();

System.out.println( "connected url: " + con.getURL() );
InputStream is = con.getInputStream();
System.out.println( "redirected url: " + con.getURL() );
is.close();

} }

It always gives original url whereas the redirectURL is:http://www.amazon.com/Kindle-Wireless-Reading-Display-Globally/dp/B003FSUDM4/ref=amb_link_353259562_2?pf_rd_m=ATVPDKIKX0DER&pf_rd_s=center-10&pf_rd_r=11EYKTN682A79T370AM3&pf_rd_t=201&pf_rd_p=1270985982&pf_rd_i=B002Y27P3M.

How can i get this final redirected URL.

Here is what i tried with looping till we get redirects.Still doesent fetch the desired url:

    public static String fetchRedirectURL(String url) throws IOException
    {
HttpURLConnection con =(HttpURLConnection) new URL( url ).openConnection();
//System.out.println( "orignal url: " + con.getURL() );
con.setInstanceFollowRedirects(false);
con.connect();


InputStream is = con.getInputStream();
if(con.getResponseCode()==301)
    return con.getHeaderField("Location");
else return null;
    }
    public static void main(String[] args) throws MalformedURLException, IOException {
String url="http://tinyurl.com/KindleWireless";
String fetchedUrl=fetchRedirectURL(url);
System.out.println("FetchedURL is:"+fetchedUrl);
while(fetchedUrl!=null)
{   url=fetchedUrl;
System.out.println("The url is:"+url);
    fetchedUrl=fetchRedirectURL(url);


}
System.out.println(url);

    }

标签: java
7条回答
不美不萌又怎样
2楼-- · 2020-01-27 08:01
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;
}
查看更多
登录 后发表回答