这种行为是故意的吗?
//create the same URI using two different constructors
URI foo = null, bar = null;
try {
//constructor: URI(uri string)
foo = new URI("http://localhost/index.php?token=4%2F4EzdsSBg_4vX6D5pzvdsMLDoyItB");
} catch (URISyntaxException e) {}
try {
//constructor: URI(scheme, authority, path, query, fragment)
bar = new URI("http", "localhost", "/index.php", "token=4%2F4EzdsSBg_4vX6D5pzvdsMLDoyItB", null);
} catch (URISyntaxException e) {}
//the output:
//foo.getQuery() = token=4/4EzdsSBg_4vX6D5pzvdsMLDoyItB
//bar.getQuery() = token=4%2F4EzdsSBg_4vX6D5pzvdsMLDoyItB
URI(string uri) 构造函数似乎正在解码 URI 的查询部分。我认为查询部分应该被编码?为什么另一个构造函数不解码查询部分?
最佳答案
来自 URI JavaDoc :
The single-argument constructor requires any illegal characters in its argument to be quoted and preserves any escaped octets and other characters that are present.
The multi-argument constructors quote illegal characters as required by the components in which they appear. The percent character ('%') is always quoted by these constructors. Any other characters are preserved.
因此 URI(String) 希望您正确编码所有内容,并假设 %2F
是这样一个编码的八位字节,它将被解码为 /
。
其他构造函数会对 %
字符进行结束编码(对于输入 %2F
产生 %252F
),因此在解码后您仍然会得到 %2F
。
我假设构造函数之间存在偏差的目的是允许诸如 new URI(otherUri.toString())
和 toString()
返回完全编码的 URI 之类的内容。
关于Java URI 类 : constructor determines whether or not query is encoded?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5828722/