[英]Java - How could change a relative URL String to an absolute URL if I know the domain?
所以我正在尝试制作一个非常基本的网络浏览器来完成非常具体的任务。 但是,我需要从相对 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.resolve()
方法。
首先从您在浏览器中加载的基本 URL 创建一个URI
:
URI uri = new URI("http://example.com/directory/page.html");
URI newpage = uri.resolve("newpage.html");
System.out.println(newpage);
这将打印:
uri.resolve("../newpage.html")
是:
uri.resolve("http://example.org/dir/anotherpage.html")
是:
当然,您可以先检查http
前缀并返回绝对 URL,而不是使用uri.resolve()
。
甚至可以使用锚点,例如#myanchor
。 uri.resolve("#myanchor")
是:
看看 Norconex commons-lang
和URLNormalizer 。 如果您想自己编写代码,请检查removeDotSegments()
方法是如何实现的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.