如何最有效地获取完整的URL地址?

时间:2011-10-17 12:37:04

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

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

Connection.getHeaderField("Location");

VS

Connection.getURL();

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

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

2 个答案:

答案 0 :(得分: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)HttpURLConnection不会遵循重定向,并且目标网页(上例中的stackoverflow.com)不会仅从bit.ly的重定向页面下载。< / p>

一个缺点是,如果已解析的bit.ly网址指向另一个短网址,例如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响应,其中包含Location标题(指向http://stackoverflow.com/)。现代浏览器不会显示上面的HTML页面。相反,他们会自动将您重定向到Location标题中的网址。

答案 1 :(得分:2)

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