R12*_*234 2 java url tinyurl bit.ly url-shortener
我正在使用Java程序从短URL获取扩展的URL.鉴于Java URLConnection,在这两种方法中,哪一种更能获得理想的结果?
Connection.getHeaderField("Location");
Run Code Online (Sandbox Code Playgroud)
VS
Connection.getURL();
Run Code Online (Sandbox Code Playgroud)
我猜两个都给出了相同的输出.第一种方法没有给我最好的结果,只有七分之一得到解决.第二种方法可以提高效率吗?
我们可以使用其他更好的方法吗?
我使用以下内容:
@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());
}
Run Code Online (Sandbox Code Playgroud)
随着setInstanceFollowRedirects(false)对HttpURLConnection不遵循重定向和目标页面(stackoverflow.com在上面的例子)将不会从下载只是重定向页面bit.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>
Run Code Online (Sandbox Code Playgroud)
如您所见,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
Run Code Online (Sandbox Code Playgroud)
它发送301 Moved Permanently带有Location标题的响应(指向http://stackoverflow.com/).现代浏览器不会显示上面的HTML页面.相反,他们会自动将您重定向到Location标题中的URL .
| 归档时间: |
|
| 查看次数: |
4264 次 |
| 最近记录: |