【问题标题】:How to get the complete URL address most efficiently?如何最有效地获取完整的 URL 地址?
【发布时间】:2011-12-09 06:42:06
【问题描述】:

我正在使用 Java 程序从短 URL 中获取扩展 URL。给定一个 Java URLConnection,在这两种方法中,哪一种更能得到想要的结果?

Connection.getHeaderField("Location");

Connection.getURL();

我猜他们都给出了相同的输出。第一种方法没有给我最好的结果,只有七分之一的解决了。第二种方法能提高效率吗?

我们可以使用其他更好的方法吗?

【问题讨论】:

  • 当你说“短 url”时,你的意思是你有一些像 tinyurl 或 bit.ly 这样的服务生成的东西吗?
  • 是的,但不限于这两个。

标签: java url url-shortener bit.ly tinyurl


【解决方案1】:

我会使用以下内容:

@Test
public void testLocation() throws Exception {
    final String link = "http://bit.ly/4Agih5";

    final URL url = new URL(link);
    final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setInstanceFollowRedirects(false);

    final String location = urlConnection.getHeaderField("location");
    assertEquals("http://stackoverflow.com/", location);
    assertEquals(link, urlConnection.getURL().toString());
}

对于setInstanceFollowRedirects(false)HttpURLConnection 不会跟随重定向,并且目标页面(上例中的stackoverflow.com)不会仅下载来自bit.ly 的重定向页面。

一个缺点是,当解析的 bit.ly URL 指向另一个短 URL(例如在 tinyurl.com 上)时,您将获得一个 tinyurl.com 链接,而不是 tinyurl.com 重定向到的链接。

编辑

要查看bit.ly 的回复,请使用curl

$ curl --dump-header /tmp/headers http://bit.ly/4Agih5
<html>
<head>
<title>bit.ly</title>
</head>
<body>
<a href="http://stackoverflow.com/">moved here</a>
</body>
</html>

如您所见,bit.ly 仅发送一个简短的重定向页面。然后检查 HTTP 标头:

$ cat /tmp/headers
HTTP/1.0 301 Moved Permanently
Server: nginx
Date: Wed, 06 Nov 2013 08:48:59 GMT
Content-Type: text/html; charset=utf-8
Cache-Control: private; max-age=90
Location: http://stackoverflow.com/
Mime-Version: 1.0
Content-Length: 117
X-Cache: MISS from cam
X-Cache-Lookup: MISS from cam:3128
Via: 1.1 cam:3128 (squid/2.7.STABLE7)
Connection: close

它发送带有Location 标头(指向http://stackoverflow.com/)的301 Moved Permanently 响应。现代浏览器不会向您显示上面的 HTML 页面。相反,它们会自动将您重定向到 Location 标头中的 URL。

【讨论】:

  • 你能解释一下最后两行是做什么的吗?我的其余代码完全相同。
  • 另外,如果我将 FollowRidirects 设置为 true,是否会显着影响性能?
  • 他们是jUnit assertion methods,他们检查第一个和第二个参数是否相等。在示例中它们是相等的。性能:如果instanceFollowRedirectstrue,则您从bit.ly 下载一个页面,然后bit.ly 重定向到第二个页面(在示例中为stackoverflow.com)。使用false,您只需下载一页,因此您使用的带宽更少。
  • @palacsint,如果我删除“urlConnection.setInstanceFollowRedirects(false);”行,就会失败。其中的原因是什么?
  • @Jacky:我已经开始编辑页面,但我意识到“会有故障”有点模棱两可。 “失败”是什么意思?
【解决方案2】:

上面的链接包含一个更完整的方法,与上一篇文章相同 https://github.com/cpdomina/WebUtils/blob/master/src/net/cpdomina/webutils/URLUnshortener.java

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 2016-11-29
    • 2013-08-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    相关资源
    最近更新 更多