java.net.URI多参数构造器疑似存在Bug?
java.net.URI多参数构造器的路径解析异常分析
我怀疑自己是否有所遗漏,或是java.net.URI类的多参数构造器存在Bug。
基础测试:仅传入路径却被解析为Scheme
执行以下代码:
URI uri = new URI( null, null, null, -1, "test:this.pdf", null, null ); System.out.println("Scheme: " + uri.getScheme()); System.out.println("Path: " + uri.getPath()); System.out.println("URI: " + uri);
输出结果显示,明明只传入了路径,却被解析出Scheme,路径信息丢失:
Scheme: test Path: null URI: test:this.pdf
带空格的路径抛出异常
如果路径中包含空格:
URI uri = new URI( null, null, null, -1, "test :this.pdf", null, null );
会抛出异常:
Illegal character in scheme name at index 4: test%20:this.pdf
添加斜杠后恢复正常
在路径中添加一个位置恰当的斜杠,代码可正常运行:
URI uri = new URI( null, null, null, -1, "test /:this.pdf", null, null );
显式设置Scheme的失败情况
尝试显式指定Scheme时,会因另一个原因失败:
URI uri = new URI( "example", null, null, -1, "test :this.pdf", null, null );
异常信息:
Relative path in absolute URI: example:test%20:this.pdf
显式编码无法解决问题
手动对冒号编码后传入,结果编码后的内容被当成路径的一部分,且原编码被二次转义:
URI uri = new URI( null, null, null, -1, "test :this.pdf".replaceAll(":", "%3A"), null, null );
输出:
Scheme: null Path: test %3Athis.pdf URI: test%20%253Athis.pdf
可行的解决办法
改用字符串参数的单参数构造器new URI(string),自行处理边缘情况并编码:
uri = new URI("test :this.pdf".replaceAll(":", "%3A").replaceAll(" ", "%20"));
可得到预期结果:
Scheme: null Path: test :this.pdf URI: test%20%3Athis.pdf
相关规范参考
In addition, a URI reference
(Section 4.1) may be a relative-path reference, in which case the
first path segment cannot contain a colon (":") character.
规范未明确说明是否允许编码后的冒号,但Java中获取URI路径时是支持这种编码形式的。由此判断,原多参数构造器存在未对冒号进行编码的缺陷。
内容的提问来源于stack exchange,提问作者nablex
相关产品推荐
相关产品推荐

