我正在尝试解析两个URI,但并不像我希望的那样简单。
URI a = new URI("http://www.foo.com");
URI b = new URI("bar.html");问题是a.resolve(b).toString()现在变成了"http://www.foo.combar.html"。我怎么才能逃脱惩罚呢?
发布于 2010-03-29 07:34:32
听起来您可能希望使用URL,而不是URI (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"URI的toString()的行为并不像您所期望的那样,但是考虑到它的一般性质,它可能是应该被原谅的。
遗憾的是,URI的toURL()方法的行为并不完全像我希望的那样。
URL u = c.toURL();
u.toString() -> "http://www.foo.combar.html"
u.getAuthority() -> "www.foo.combar.html" --- Oh dear :(所以最好直接从开始获取你想要的:
URL x = new URL("http://www.foo.com");
URL y = new URL(x, "bar.html");
y.toString() -> "http://www.foo.com/bar.html"发布于 2011-08-16 23:19:47
URI还应该包含最后的分隔符(‘/’),以解析您想要的方式:
URI a = new URI("http://www.foo.com/");发布于 2019-11-13 19:00:32
URI.resolve的行为就像你在一个像http://example.org/path/to/menu.html这样的超文本标记语言页面上,点击一个带有href="page1.html"的链接:它切掉最后一段(这里是menu.html),并把page1.html放在它的位置上。
(http://example.org/path/to/menu.html,page1.html) http://example.org/path/to/page1.html→
如果在上调用resolve的对象是一个目录(以斜杠:结尾表示),这也是有效的
(http://example.org/path/to/,page1.html) http://example.org/path/to/page1.html→
如果it 不是以斜杠结尾,则结果可能不是您所期望的:
(http://example.org/path/to,page1.html) http://example.org/path/page1.html→(缺少"to")
如果您知道要连接的URI的第一个参数是一个目录,但您不知道以哪种格式获得它(带或不带尾部斜杠),这可能会对您有所帮助:
static URI asDirectory(URI uri) {
String uriString = uri.toString();
return !uriString.endsWith("/") ? URI.create(uriString.concat("/")) : uri;
}https://stackoverflow.com/questions/2534124
复制相似问题