12

Sometimes my URL will redirect to a new page, so I want to get the URL of the new page.

Here is my code:

URL url = new URL("http://stackoverflow.com/questions/88326/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(true);

System.out.println(conn.getURL().toString());

The output is:

stackoverflow.com/questions/88326/does-elmah-handle-caught-exceptions-as-well

It works well for the Stack Overflow website, but for the sears.com site, it doesn't work.

If we enter the URL blow:

http://www.sears.com/search=iphone

the output is still:

http://www.sears.com/search=iphone

But actually, the page will redirect to:

http://www.sears.com/tvs-electronics-phones-all-cell-phones/s-1231477012?keyword=iphone&autoRedirect=true&viewItems=25&redirectType=CAT_REC_PRED

How can I solve this problem?

syb0rg
  • 8,057
  • 9
  • 41
  • 81
user2105500
  • 197
  • 1
  • 2
  • 8
  • The Sears link is not a HTTP redirect: `curl --head -I http://www.sears.com/search=iphone`. It probably redirects through JavaScript. – apricot Feb 07 '18 at 22:48

2 Answers2

21

Simply call getUrl() on URLConnection instance after calling getInputStream():

URLConnection con = new URL(url).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();

If you need to know whether the redirection happened before actually getting it's contents, here is the sample code:

HttpURLConnection con = (HttpURLConnection) (new URL(url).openConnection());
con.setInstanceFollowRedirects(false);
con.connect();
int responseCode = con.getResponseCode();
System.out.println(responseCode);
String location = con.getHeaderField("Location");
System.out.println(location);
syb0rg
  • 8,057
  • 9
  • 41
  • 81
  • 2
    but still not works for "http:// www.sears.com/search=iphone", could please please help me figure out what's up? – user2105500 Feb 24 '13 at 23:03
  • your code works for stackoverflow.com/questions/88326/, but not for sear.com I guess maybe sear.com is not an redirect. It is get something from server. – user2105500 Feb 24 '13 at 23:16
  • The Sears link is not a HTTP redirect: `curl --head -I http://www.sears.com/search=iphone`. It probably redirects through JavaScript. – apricot Feb 07 '18 at 22:50
  • 1
    This doesn't work for me. I'm trying to expand this url http://skl.sh/thomasfrank11 but I get the same url when I do con.getUrl() – Jonathan Morales Vélez Dec 05 '18 at 15:42
1

actually we can use HttpClient, which we can set HttpClient.followRedirect(true) HttpClinent will handle the redirect things.

user2105500
  • 197
  • 1
  • 2
  • 8