我有一個重定向到另一個url.I一個網址希望能夠獲得最後的重定向URL.My代碼:的java的URLConnection得到最終的重定向的URL
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();
}}
它總是給出原始的url,而redirectURL是: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。
我怎樣才能得到這個最終重定向的URL。
這裏是我試圖與循環,直到我們得到redirects.Still doesent獲取所需的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);
}
@ SJuan76驚喜驚喜 - 我沒有得到我的機器上相同的行爲 - MACOSX ..我正在重新定向值....... .......... orignal url:http://tinyurl.com/KindleWireless 連接網址:http://tinyurl.com/KindleWireless 重定向網址:http://www.amazon.com/Kindle -Keyboard-Free-Wi-Fi-Display/dp/B004HZYA6E – user1428716 2013-02-19 07:23:49
但我們得到的重定向url不是最終的url。最終的url是我粘貼的。如果你將tinyUrl粘貼到瀏覽器中,那麼你得到的最終url是:http ://www.ama zon.com/Kindle-Wireless-Reading-Display-Globally/dp/B003FSUDM4/ref=amb_link_353259562_2?pf_rd_m = ATVPDKIKX0DER&pf_rd_s =中心10 pf_rd_r = 11EYKTN682A79T370AM3&pf_rd_t = 201&pf_rd_p = 1270985982&pf_rd_i = B002Y27P3M – Jeets 2013-02-19 07:54:48
@Jeets具有u讓你的question.because的答案我面臨同樣的問題.. – dipali 2015-10-28 07:15:42