为什么下面的代码不会抛出 URISyntaxException
在运行时作为非法 URI?
new URI("http:us//er:ps//w@si//te.c/om/dir1/di//r2/fi//le.txt#frag//ment");
// or same with "http:// ... "
new URI("http://us//er:ps//w@si//te.c/om/dir1/di//r2/fi//le.txt#frag//ment");
根据wikipedia “/
”是保留(特殊)字符,应将其百分比编码(也称为 URL 编码)为 %2F
The reserved character
/
, for example, if used in the "path" component of a URI, has the special meaning of being a delimiter between path segments. If, according to a given URI scheme,/
needs to be in a path segment, then the three characters%2F
or%2f
must be used in the segment instead of a raw/
.
但是 URI 构造函数不允许对其进行 URL 编码!
维基百科 defines URI 格式如下(RFC 3986,第 3 节 (2005)):
URI = scheme:[//authority]path[?query][#fragment]
URI 构造函数允许直接使用 /
(不是百分比编码)在任何组件中(也许方案除外)。
URI Javadoc states :
This constructor parses the given string exactly as specified by the grammar in RFC 2396, Appendix A, except for the following deviations: ...
Characters in the other category are permitted wherever RFC 2396 permits escaped octets, that is, in the user-information, path, query, and fragment components, as well as in the authority component if the authority is registry-based. This allows URIs to contain Unicode characters beyond those in the US-ASCII character set.
这允许非百分比编码的“其他”字符(请参阅上面的 wiki 链接以了解保留/非保留/其他字符的说明),例如 ɷ(非 ASCII),因此这与保留无关诸如正斜杠之类的字符。
但无论如何 - 为什么以及为什么?
附注维基百科解释了为什么我们可以在其他组件中使用正斜杠,但为什么我们可以在路径组件(目录名、文件名)中使用它还不清楚。
Reserved characters that have no reserved purpose in a particular context may also be percent-encoded but are not semantically different from those that are not.
在 URI 的“查询”部分(? 字符后面的部分),对于 例如,/仍被视为保留字符 但通常 没有保留目的,除非特定的 URI 方案表明 否则。该字符不需要进行百分比编码 没有保留目的。
block 引用>
最佳答案
好的,所以问题实际上是为什么 URI 的路径元素允许/。
在第一个维基百科注释中,您清楚地表明/是路径段之间的分隔符。 (路径元素!=路径段)
您必须转义路径段内的内容。
您不能转义DELIMIT路径段
URI:http://address.com/path%2fSegment1/path%2fSegment2/path%2fSegment3
关于java - 为什么 URI 构造函数允许在其 URI 参数中使用非百分比编码的保留特殊字符(正斜杠)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53805960/