gpt4 book ai didi

java - 如何最高效的获取完整的URL地址?

转载 作者:行者123 更新时间:2023-12-02 00:47:39 25 4
gpt4 key购买 nike

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

Connection.getHeaderField("Location");

对比

Connection.getURL();

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

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

最佳答案

我会使用以下内容:

@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 header :

$ 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 header (指向 http://stackoverflow.com/)的 301 Moved Permanently 响应。现代浏览器不会向您显示上面的 HTML 页面。相反,它们会自动将您重定向到 Location header 中的 URL。

关于java - 如何最高效的获取完整的URL地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7793827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com