我会使用以下内容:
@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。