为什么下面的代码在运行时不会将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");
根据维基百科," /"是保留的(特殊)字符,并且应按百分比编码(也称为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编码!
Wikipedia定义URI格式如下(RFC 3986,第3部分(2005年)):
URI = scheme:[//authority]path[?query][#fragment]
URI构造函数允许在任何组件中直接使用/(未经百分比编码)(可能是方案的例外)。
URI Javadoc指出:
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),因此这与保留字符(例如正斜杠)无关。
但是无论如何-为什么以及为什么呢?
附言Wikipedia解释了为什么我们可以在其他组件中使用正斜杠,但是为什么我们不能在路径组件(目录名,文件名)中使用它。
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方案指出
除此以外。字符在字符时不需要进行百分比编码
没有保留的目的。
blockquote>
您特别希望哪个斜杠引起异常?
任何单个/路径中的组件,在这里就是两种情况:.... di // r2 / fi // le.txt ...-目录dir2名称的中间和文件file.txt的中间 。
好的,所以问题实际上是为什么URI的path元素允许/。 在第一个Wikipedia注释中,您清楚地显示了/是路径段之间的分隔符。 您必须将路径段中的那些转义。 您不得转义分隔路径段的内容。
"维基百科对URI格式的定义如下……"并非完全如此。 维基百科和URI规范将分层URI定义为scheme:[authority]path[?query][#fragment]。 由于URI中http:后面的字符不是斜杠,因此您根本没有分层URI,因此唯一的字符限制是规范术语uric(包括斜杠)。
好的,所以问题实际上是为什么URI的path元素允许/。
在第一个Wikipedia注释中,您清楚地显示了/是路径段之间的分隔符。 (路径元素!=路径段)
您必须在路径段内转义那些。
您不得转义使用DELIMIT路径分段的内容
URI:http://address.com/path%2fSegment1/path%2fSegment2/path%2fSegment3
链接断开(从台式机查看)。 附言 感谢您指出路径元素!=路径段!
抱歉,我仍然无法理解site.com/dir1/dir2/file.html中的路径段和路径元素