【问题标题】:Java - How could change a relative URL String to an absolute URL if I know the domain?Java - 如果我知道域,如何将相对 URL 字符串更改为绝对 URL?
【发布时间】:2019-08-15 01:40:25
【问题描述】:

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

我使用 Java 6 是为了与旧系统(很多旧)兼容

基本上,我有 URL“http://example.com/directory/page.html”,然后我有一个带有 href=“newpage.html”的标签。我希望能够获得 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"。

有什么好的、干净的方法吗?

【问题讨论】:

  • 将其转换为URI 并使用其方法,然后将其转换回来。您不必担心双点。 Web 服务器会理解它们。

标签: java url href java-6


【解决方案1】:

您可以简单地使用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 前缀并返回绝对 URL,而不是使用 uri.resolve()

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

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

【讨论】:

  • 完全按照我的意愿工作!谢谢!
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 2014-12-12
    相关资源
    最近更新 更多