URI和双斜杠

问题描述

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

将主机用作IP地址时,是否需要双斜杠?我浏览了RFC的URI-https://tools.ietf.org/html/rfc3986。但是找不到与此有关的任何东西。

解决方法

java.net.URI.create uses the syntax,如RFC 2396中所述。

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

这不会产生异常,但是会以您可能不希望的方式解析URI。其方案(不是主机!)设置为localhost,而8080/foo不是端口+路径,而是方案特定的部分 。因此,这实际上不起作用。

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

解析不带方案的URL,将其作为 net_path 语法元素(有关详细信息,请参阅RFC 2396)。

以下是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 | "+" | "-" | "." )

一种正确的方法是:

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