java urlconnection pobiera ostateczny przekierowany adres URL
Mam adres URL, który przekierowuje do innego adresu URL. Chcę mieć możliwość uzyskania ostatecznego przekierowanego adresu URL.Mój kod:
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();
}}
Zawsze podaje oryginalny adres URL, podczas gdy redirectURL to:http://www.amazon.com/Kindle-Wireless-Reading-Display-Globally/dp/B003FSUDM4/ref=amb_link_353259562_2?.
Jak mogę uzyskać ten ostateczny przekierowany adres URL.
Oto, co próbowałem zapętlić, dopóki nie otrzymamy przekierowań. Wciąż nie pobieramy żądanego adresu 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);
}