我正在尝试解析两个URI,但它并不像我希望的那样直截了当.
URI a = new URI("http://www.foo.com");
URI b = new URI("bar.html");
Run Code Online (Sandbox Code Playgroud)
麻烦a.resolve(b).toString()就是现在"http://www.foo.combar.html".我怎么能逃脱呢?
Mik*_*ffe 29
听起来你可能想要使用URL而不是URI(这是更通用的,需要处理不太严格的语法.)
URI a = new URI("http://www.foo.com");
URI b = new URI("bar.html");
URI c = a.resolve(b);
c.toString() -> "http://www.foo.combar.html"
c.getAuthority() -> "www.foo.com"
c.getPath() -> "bar.html"
Run Code Online (Sandbox Code Playgroud)
URI的toString()不会像你期望的那样表现,但考虑到它的一般性质,它可能应该被宽恕.
遗憾的是,URI的toURL()方法并不像我希望的那样表达你想要的东西.
URL u = c.toURL();
u.toString() -> "http://www.foo.combar.html"
u.getAuthority() -> "www.foo.combar.html" --- Oh dear :(
Run Code Online (Sandbox Code Playgroud)
所以最好只是直接用URL来获得你想要的东西:
URL x = new URL("http://www.foo.com");
URL y = new URL(x, "bar.html");
y.toString() -> "http://www.foo.com/bar.html"
Run Code Online (Sandbox Code Playgroud)
URI.resolve 的行为就像您在 HTML 页面上一样http://example.org/path/to/menu.html,然后单击带有 的链接href="page1.html":它会切断最后一段(此处menu.html)并page1.html放在其位置。
( http://example.org/path/to/menu.html,page1.html) \xe2\x86\x92http://example.org/path/to/page1.html
如果您调用的对象解析,这也有效是一个目录(以斜杠结尾表示),这也适用:
\n\n( http://example.org/path/to/,page1.html) \xe2\x86\x92http://example.org/path/to/page1.html
如果它不以斜杠结尾,结果不是您所期望的:
\n\n( http://example.org/path/to, page1.html) \xe2\x86\x92http://example.org/path/page1.html(缺少“to”)
如果你知道的话要连接的 URI 的第一个参数是一个目录,但您不知道以哪种格式获取它(带或不带尾部斜杠),这可能会帮助您:
\n\nstatic URI asDirectory(URI uri) {\n String uriString = uri.toString();\n return !uriString.endsWith("/") ? URI.create(uriString.concat("/")) : uri;\n}\nRun Code Online (Sandbox Code Playgroud)\n
小智 5
URI应该包含最终的分隔符('/')以解决您想要的方式:
URI a = new URI("http://www.foo.com/");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16163 次 |
| 最近记录: |