【问题标题】:is it possible to know if the url is redirecting是否可以知道网址是否正在重定向
【发布时间】:2017-11-08 23:57:37
【问题描述】:

我正在用 java 开发一个应用程序来验证一个站点是否在线。 我通过以下方式获得 http 响应:

URL url = new URL("http://www.example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

但是当我访问它正在重定向的 URL 时,HTTP 响应始终是 301。我想获取该站点被重定向的新 URL。可能吗?

【问题讨论】:

  • 您需要将 follow redirect 设置为 true,api 将加载重定向页面,然后您可以按照其他人的建议检查位置标头。
  • HttpURLConnection 默认自动跟随重定向。如果您收到 301,则您必须使用 setFollowRedirectssetInstanceFollowRedirects 方法明确禁用以下重定向,但您没有在问题中提及。
  • @ErwinBolwidt 我试图获得响应的站点给了我一个 301 和 302 HTTP 响应。但是使用 getHeaderField() 我只能得到旧的 URL

标签: java url http-redirect


【解决方案1】:

重定向的目标在响应的HTTP Header中,寻找“Location”头。

【讨论】:

【解决方案2】:

您可以使用以下方式访问标题:

String redirectUrl = connection.getHeaderField("Location");

【讨论】:

  • 我在标题中得到了 URL,但它是一样的。我实际上得到了两个 HTTP 响应,一个是 301,另一个是 302。是不是改变了我获取 header 的方式?
  • @ThalesFlores 你确定是同一个 URL 吗?或者它可能以https 而不是http 开头?
  • 我访问的站点是 https,当它被重定向到 http 时。但是当我的代码运行时,我只得到 https URL。
  • 这很奇怪,因为该方法应该像这个例子一样获得最终的重定向:URL url = new URL("http://www.microsoft.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); String redirectUrl = connection.getHeaderField("Location"); System.out.println(redirectUrl);
  • @OmarEDDASSER 我自己再次导入了 API,现在它可以工作了。感谢您的关注
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-20
  • 2017-09-04
  • 1970-01-01
  • 2016-10-06
  • 2023-03-17
  • 2013-09-13
相关资源
最近更新 更多