-2

original url : http://pricecheckindia.com/go/store/ebay/52440?ref=velusliv

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

I need a program that will take the original url and print the redirected url.

How to get this done in 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());
}

1 Answers1

2

It seems that you are being redirected via JavaScript code, which Jsoup doesn't support (it is simple HTML parser, not browser emulator). Your choice then is to either use tool which will support JavaScript like Selenium web driver, or parse your page to get url from click here link from

If it is taking too long to redirect, then please click here

text.

You can use Jsoup to get this link by adding to your current code

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

which will return and print

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

so now all we need to do is parse query from this URL to get value of mpre key, which encoded version looks like

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

but after decoding it will actually represents

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

To get value of this key and decode it you can use one of solutions from this question: Parse a URI String into Name-Value Collection. With help of method from accepted answer in previously mentioned question we can just invoke

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

to see result

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

Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269