javaurirfc3986

URI and double slashes


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.


Solution

  • 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")