2014-09-26 38 views
-2

原始地址:http://pricecheckindia.com/go/store/ebay/52440?ref=velusliv的Java打印重定向的URL

重定向的URL:http://www.ebay.in/itm/Asus-Zenfone-6-A600CG-A601CG-White-16-GB-/111471688863?pt=IN_Mobile_Phones&aff_source=DA

我需要一個程序,將採取original url並打印redirected url

如何在java中完成此操作。

public static void main(String[] args) throws IOException, InterruptedException 
{ 
    String url = "http://pricecheckindia.com/go/store/ebay/52440?ref=velusliv"; 
    Response response = Jsoup.connect(url).followRedirects(false).execute(); 
    System.out.println(response.url()); 
} 
+0

試圖jsoup的東西......但沒有得到它的權利 – 2014-09-26 17:47:54

回答

2

看起來你正在通過JavaScript代碼重定向,Jsoup不支持它(它是簡單的HTML解析器,而不是瀏覽器模擬器)。然後,您的選擇是,要麼使用工具,這將支持JavaScript像硒網絡驅動程序,或者如果時間太長重定向,那麼請click here

解析你的頁面從click here鏈接獲取網址

文字。

可以使用Jsoup通過添加到您當前密碼

Document doc = response.parse(); 
String redirectUrl = doc.select("a:contains(click here)").attr("href"); 
System.out.println(redirectUrl); 

哪那麼現在我們需要做的將返回並打印

http://rover.ebay.com/rover/1/4686-127726-2357-15/2?&site=Partnership_PRCCHK&aff_source=DA&mpre=http%3A%2F%2Fwww.ebay.in%2Fitm%2FAsus-Zenfone-6-A600CG-A601CG-White-16-GB-%2F111471688863%3Fpt%3DIN_Mobile_Phones%26aff_source%3DDA

得到這個鏈接解析來自此URL的查詢以獲得值爲mpre的密鑰,該編碼版本看起來像

http%3A%2F%2Fwww.ebay.in%2Fitm%2FAsus-Zenfone-6-A600CG-A601CG-White-16-GB-%2F111471688863%3Fpt%3DIN_Mobile_Phones%26aff_source%3DDA

但解碼之後它實際上代表

http://www.ebay.in/itm/Asus-Zenfone-6-A600CG-A601CG-White-16-GB-/111471688863?pt=IN_Mobile_Phones&aff_source=DA

爲了得到這個鍵的值,並對其進行解碼,您可以使用解決方案之一,從這個問題:Parse a URI String into Name-Value Collection。與前面提到的問題,接受的答案方法的幫助下,我們可以只調用

URL address = new URL(redirectUrl); 
Map<String,List<String>> urlQuerryMap= splitQuery(address); 
String redirected = urlQuerryMap.get("mpre").get(0); 
System.out.println(redirected); 

看到導致

http://www.ebay.in/itm/Asus-Zenfone-6-A600CG-A601CG-White-16-GB-/111471688863?pt=IN_Mobile_Phones&aff_source=DA