2

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

Connection.getHeaderField("Location");

对比

Connection.getURL();

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

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

4

2 回答 2

5

我会使用以下内容:

@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)在上面的示例中)将不会仅下载来自的重定向页面。HttpURLConnectionstackoverflow.combit.ly

一个缺点是,当解析的bit.lyURL 指向另一个短 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

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

于 2011-10-17T13:34:23.663 回答
2

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

于 2012-05-11T21:26:29.580 回答