如何最有效地获取完整的URL地址?
我正在使用Java程序从短URL获取扩展的URL。 给定Java URLConnection
,在这两种方法中,哪一种更好地获得所需的结果?
Connection.getHeaderField("Location");
VS
Connection.getURL();
我猜两个都给出了相同的输出。 第一种方法没有给我最好的结果,只有7个中的1个得到了解决。 第二种方法可以提高效率吗?
我们可以使用其他更好的方法吗?
我使用以下内容:
@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 bit.ly moved here
正如您所见, 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
标头发送301 Moved Permanently
响应(指向http://stackoverflow.com/
)。 现代浏览器不会显示上面的HTML页面。 相反,它们会自动将您重定向到Location
标头中的URL。
上面的链接包含一个比上一篇文章更完整的方法https://github.com/cpdomina/WebUtils/blob/master/src/net/cpdomina/webutils/URLUnshortener.java