gpt4 book ai didi

java - 如何使用 HttpURLConnection 获取重定向的 URL 和内容

转载 作者:搜寻专家 更新时间:2023-10-30 21:44:35 25 4
gpt4 key购买 nike

有时候我的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 blow:

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

我该如何解决这个问题?

最佳答案

在调用 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/15057329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com