私は以下を使用します:
@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。
1つの欠点は、解決されたbit.lyURLが別の短いURLを指している場合、たとえば、リダイレクト先ではなく、リンクtinyurl.comを取得することです。tinyurl.comtinyurl.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