Difference between opaque and hierarchical URI?

2019-06-16 05:55发布

问题:

What is the Difference between opaque and hierarchical URI in context of java networking ?

回答1:

A typical example of an opaque uri is a mail to url mailto:a@b.com. They differ from a hierarchical uri in that they don't describe a path to a resource.

Therefore a Uri that is opaque returns null for getPath.

Some examples:

public static void main(String[] args) {
    printUriInfo(URI.create("mailto:a@b.com"));
    printUriInfo(URI.create("http://example.com"));
    printUriInfo(URI.create("http://example.com/path"));
    printUriInfo(URI.create("scheme://example.com"));
    printUriInfo(URI.create("scheme:example.com"));
    printUriInfo(URI.create("scheme:example.com/path"));
    printUriInfo(URI.create("path"));
    printUriInfo(URI.create("/path"));
}

private static void printUriInfo(URI uri) {
    System.out.println(String.format("Uri [%s]", uri));
    System.out.println(String.format(" is %sopaque", uri.isOpaque() ? "" : "not "));
    System.out.println(String.format(" is %sabsolute", uri.isAbsolute() ? "" : "not "));
    System.out.println(String.format(" Path [%s]", uri.getPath()));
}

Prints:

Uri [mailto:a@b.com]
 is opaque
 is absolute
 Path [null]
Uri [http://example.com]
 is not opaque
 is absolute
 Path []
Uri [http://example.com/path]
 is not opaque
 is absolute
 Path [/path]
Uri [scheme://example.com]
 is not opaque
 is absolute
 Path []
Uri [scheme:example.com]
 is opaque
 is absolute
 Path [null]
Uri [scheme:example.com/path]
 is opaque
 is absolute
 Path [null]
Uri [path]
 is not opaque
 is not absolute
 Path [path]
Uri [/path]
 is not opaque
 is not absolute
 Path [/path]


回答2:

This is explained by the javadoc for the URI class:

"A URI is opaque if, and only if, it is absolute and its scheme-specific part does not begin with a slash character ('/'). An opaque URI has a scheme, a scheme-specific part, and possibly a fragment; all other components are undefined."

The "components" it is referring to are the values returned by various URI getters.

Apart from that the "difference" comprises the inherent difference between opaque and hierarchical URIs as per the relevant specifications; e.g.

  • RFC 3986 - "Uniform Resource Identifier (URI): Generic Syntax"

Those differencese are in no way Java specific.



标签: java uri