URI和双斜杠

huangapple go评论67阅读模式
英文:

URI and double slashes

问题

java.net.URI.create("localhost:8080/foo")   // 正常工作

java.net.URI.create("127.0.0.1:8080/foo")   // 抛出异常

java.net.URI.create("//127.0.0.1:8080/foo") // 正常工作

双斜杠是否在主机为IP地址时是必需的?我浏览了URI的RFC - https://www.rfc-editor.org/rfc/rfc3986,但没有找到相关内容。

英文:
java.net.URI.create("localhost:8080/foo")   // Works

java.net.URI.create("127.0.0.1:8080/foo")   // Throws exception

java.net.URI.create("//127.0.0.1:8080/foo") // Works

Is double slash required for when you have the host as an IP Address? I glanced through the RFC for URI - https://www.rfc-editor.org/rfc/rfc3986. But could not find anything pertaining to this.

答案1

得分: 5

java.net.URI.create 使用的语法RFC 2396 中有描述。

java.net.URI.create("localhost:8080/foo")   

这并不会产生异常,但是该 URI 会以一种您可能不太预期的方式进行解析。它的 scheme(而不是主机!)被设置为 localhost,而 8080/foo 不是端口 + 路径,而是一个 scheme-specific part。因此,这实际上无法正常工作。

java.net.URI.create("//localhost:8080/foo")   

会将 URL 解析为没有 scheme 的 net_path 语法元素(详见 RFC 2396)。

以下是来自 RFC 2396 的相关语法摘录:

URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]

// 这是 'localhost:8080/foo' 的解析方式:
absoluteURI   = scheme ":" ( hier_part | opaque_part )

relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]

... 

// 这是 '//127.0.0.1:8080/foo' 的解析方式:
net_path      = "//" authority [ abs_path ]

...

// Scheme 必须以字母开头,
// 因此 'localhost' 被解析为 scheme,但 '127' 不会:
scheme        = alpha *( alpha | digit | "+" | "-" | "." )

一个正确的方法是:

java.net.URI.create("http://localhost:8080/foo")
英文:

java.net.URI.create uses the syntax described in RFC 2396.

java.net.URI.create("localhost:8080/foo")   

This doesn't produce an exception, but the URI is parsed in a way which you probably don't expect. Its scheme (not host!) is set to localhost, and the 8080/foo isn't port + path, but a scheme-specific part. So this doesn't really work.

java.net.URI.create("//localhost:8080/foo")   

parses the URL without scheme, as a net_path grammar element (see RFC 2396 for details).

Here's the relevant grammar excerpt from the RFC 2396:

URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]

// This is how 'localhost:8080/foo' is parsed:
absoluteURI   = scheme ":" ( hier_part | opaque_part )

relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]

... 

// This is how '//127.0.0.1:8080/foo' is parsed: 
net_path      = "//" authority [ abs_path ]

...

// Scheme must start with a letter, 
// hence 'localhost' is parsed as a scheme, but '127' isn't: 
scheme        = alpha *( alpha | digit | "+" | "-" | "." )

One proper way would be:

java.net.URI.create("http://localhost:8080/foo")   

huangapple
  • 本文由 发表于 2020年10月24日 21:08:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/64513631.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定