【问题标题】:URI and double slashesURI 和双斜杠
【发布时间】:2021-02-07 07:45:26
【问题描述】:
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 地址时是否需要双斜杠?我浏览了 URI 的 RFC - https://www.rfc-editor.org/rfc/rfc3986。但找不到与此相关的任何内容。

【问题讨论】:

    标签: java uri rfc3986


    【解决方案1】:

    java.net.URI.createuses the syntaxRFC 2396 中描述。

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

    这不会产生异常,但 URI 的解析方式可能出乎您的意料。它的方案(不是主机!)设置为localhost8080/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")   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-25
      • 1970-01-01
      • 2010-12-14
      • 2012-02-10
      • 1970-01-01
      • 2011-05-15
      • 2017-05-18
      相关资源
      最近更新 更多