Java - 如果我知道域,如何将相对 URL 字符串更改为绝对 URL 字符串?

Java - How could change a relative URL String to an absolute URL if I know the domain?

所以我正在尝试制作一个非常基本的网络浏览器来完成非常具体的任务。但是,我需要从相对 URLs 中获取 URL (例如在标签中。我可以同时获取两个 URLs,但我不确定如何处理相对 URLs.

我正在使用 Java 6 来兼容旧系统(旧很多)

基本上,我有URL“http://example.com/directory/page.html", then I have an tag with the href= "newpage.html". I want to be able to get the URL "http://example.com/directory/newpage.html”。

此外,如果它的href=“../newpage.html”,我想得到“http://example.com/newpage.html”,

如果它的 href="http://example.org/dir/anotherpage.html",我想得到 URL“http://example.org/dir/anotherpage.html”。

有什么好的、干净的方法可以做到这一点吗?

看看 Norconex commons-langURLNormalizer。如果您想自己编写代码,请检查方法 removeDotSegments() 是如何实现的。

您可以简单地使用 uri.resolve() 方法。

首先从您在浏览器中加载的基础 URL 创建一个 URI

URI uri = new URI("http://example.com/directory/page.html");
URI newpage = uri.resolve("newpage.html");
System.out.println(newpage);

这将打印:

http://example.com/directory/newpage.html

uri.resolve("../newpage.html") 的结果是:

http://example.com/newpage.html

uri.resolve("http://example.org/dir/anotherpage.html") 的结果是:

http://example.org/dir/anotherpage.html

当然你可以检查前面的 http 前缀和 return 绝对 URL 而不是使用 uri.resolve().

甚至可以使用锚点,例如 #myanchoruri.resolve("#myanchor")的结果是:

http://example.com/directory/page.html#myanchor