有时我的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 网站,则不起作用。
如果我们输入以下 URL:
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
如何解决这个问题?
最佳答案
在调用 getInputStream()
后,只需在 URLConnection
实例上调用 getUrl()
即可:
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);
关于java - 如何使用 HttpURLConnection 获取重定向的 URL 和内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38673783/