2013-02-24 246 views
9

有时我的URL会重定向到一个新页面,所以我想获取新页面的URL。如何使用HttpURLConnection获取重定向的URL和内容

这里是我的代码:

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

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

输出是:

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

它适用于堆栈溢出网站,但对于sears.com网站,它不起作用。

如果我们输入URL的打击:

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

输出仍然是:

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

但实际上,该页面会重定向到:

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

我该如何解决这个问题?

+0

Sears链接不是HTTP重定向:'curl - head -I http:// www.sears.com/search = iphone'。它可能通过JavaScript重定向。 – apricot 2018-02-07 22:48:38

回答

1

其实我们可以用HttpClient,我们可以设置HttpClient.followRedirect(true) HttpClinent会处理重定向的东西。

+0

这是最好的方法......或者你必须重复地在头部重定向链接......这是太复杂了... – user2105500 2014-02-26 04:36:44

+0

谨慎地阐述你做了什么?我处于类似的情况 – 2015-09-21 17:18:58

18

简单地调用URLConnection例如getUrl()调用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(); 

如果您需要知道重定向是否真正得到它的内容,这里是示例代码之前发生的事情:

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); 
+2

,但仍然不适用于“http:// www.sears.com/search=iphone”,请请帮我弄清楚发生了什么事? – user2105500 2013-02-24 23:03:57

+0

然后你做错了什么,因为我的代码有效。 – syb0rg 2013-02-24 23:04:37

+0

您的代码适用于stackoverflow.com/questions/88326/,但不适用于sear.com我想也许sear.com不是重定向。它是从服务器获取的东西。 – user2105500 2013-02-24 23:16:59

-1

尝试HtmlUnit

final WebClient webClient = new WebClient(); 
HtmlPage page = webClient.getPage("http://www.sears.com/search=phone"); 
String finalUrl = page.getUrl().toString(); // the redirected url