12

有时我的 URL 会重定向到新页面,所以我想获取新页面的 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

它适用于 Stack Overflow 网站,但不适用于 sears.com 网站。

如果我们输入网址一击:

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

我怎么解决这个问题?

4

2 回答 2

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);
于 2013-02-24T22:20:29.330 回答
1

实际上我们可以使用 HttpClient,我们可以设置 HttpClient.followRedirect(true) HttpClinent 将处理重定向的事情。

于 2014-02-22T19:20:17.667 回答