有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

所以我正在尝试制作一个非常基本的网络浏览器来完成非常具体的任务。但是,我需要从相对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

有什么好的干净的方法吗


共 (2) 个答案

  1. # 1 楼答案

    您可以简单地使用^{}方法

    首先从浏览器中加载的基本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()

    甚至使用锚,比如#myanchor也是可能的。{}的结果是:

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

  2. # 2 楼答案

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