APIdia Launch Partner
Top Description Inners Fields Constructors Methods
java.net

public final Class URI

extends Object
implements Comparable<URI>, Serializable
Class Inheritance
All Implemented Interfaces
java.io.Serializable, java.lang.Comparable
Annotations
@AOTSafeClassInitializer
Imports
java.io.File, .IOException, .InvalidObjectException, .ObjectInputStream, .ObjectOutputStream, .Serializable, java.nio.ByteBuffer, .CharBuffer, java.nio.charset.CharsetDecoder, .CharsetEncoder, .CoderResult, .CodingErrorAction, .CharacterCodingException, java.nio.file.Path, java.text.Normalizer, jdk.internal.access.JavaNetUriAccess, .SharedSecrets, jdk.internal.util.Exceptions, jdk.internal.vm.annotation.AOTSafeClassInitializer, sun.nio.cs.UTF_8

Represents a Uniform Resource Identifier (URI) reference.

Aside from some minor deviations noted below, an instance of this class represents a URI reference as defined by RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax, amended by RFC 2732: Format for Literal IPv6 Addresses in URLs. The Literal IPv6 address format also supports scope_ids. The syntax and usage of scope_ids is described here. This class provides constructors for creating URI instances from their components or by parsing their string forms, methods for accessing the various components of an instance, and methods for normalizing, resolving, and relativizing URI instances. Instances of this class are immutable.

URI syntax and components

At the highest level a URI reference (hereinafter simply "URI") in string form has the syntax
[scheme:]scheme-specific-part[#fragment]
where square brackets [...] delineate optional components and the characters : and # stand for themselves.

An absolute URI specifies a scheme; a URI that is not absolute is said to be relative. URIs are also classified according to whether they are opaque or hierarchical.

An opaque URI is an absolute URI whose scheme-specific part does not begin with a slash character ('/'). Opaque URIs are not subject to further parsing. Some examples of opaque URIs are:

A hierarchical URI is either an absolute URI whose scheme-specific part begins with a slash character, or a relative URI, that is, a URI that does not specify a scheme. Some examples of hierarchical URIs are:

http://example.com/languages/java/
sample/a/index.html#28
../../demo/b/index.html
file:///~/calendar

A hierarchical URI is subject to further parsing according to the syntax

[scheme:][//authority][path][?query][#fragment]
where the characters :, /, ?, and # stand for themselves. The scheme-specific part of a hierarchical URI consists of the characters between the scheme and fragment components.

The authority component of a hierarchical URI is, if specified, either server-based or registry-based. A server-based authority parses according to the familiar syntax

[user-info@]host[:port]
where the characters @ and : stand for themselves. Nearly all URI schemes currently in use are server-based. An authority component that does not parse in this way is considered to be registry-based.

The path component of a hierarchical URI is itself said to be absolute if it begins with a slash character ('/'); otherwise it is relative. The path of a hierarchical URI that is either absolute or specifies an authority is always absolute.

All told, then, a URI instance has the following nine components:

Describes the components of a URI:scheme,scheme-specific-part,authority,user-info,host,port,path,query,fragment
ComponentType
schemeString
scheme-specific-partString
authorityString
user-infoString
hostString
portint
pathString
queryString
fragmentString
In a given instance any particular component is either undefined or defined with a distinct value. Undefined string components are represented by null, while undefined integer components are represented by -1. A string component may be defined to have the empty string as its value; this is not equivalent to that component being undefined.

Whether a particular component is or is not defined in an instance depends upon the type of the URI being represented. An absolute URI has a scheme component. An opaque URI has a scheme, a scheme-specific part, and possibly a fragment, but has no other components. A hierarchical URI always has a path (though it may be empty) and a scheme-specific-part (which at least contains the path), and may have any of the other components. If the authority component is present and is server-based then the host component will be defined and the user-information and port components may be defined.

Operations on URI instances

The key operations supported by this class are those of normalization, resolution, and relativization.

Normalization is the process of removing unnecessary "." and ".." segments, and redundant "/" (empty segments) from the path component of a hierarchical URI. Each "." and empty segment is simply removed. A ".." segment is removed only if it is preceded by a non-".." segment. Normalization has no effect upon opaque URIs.

Resolution is the process of resolving one URI against another, base URI. The resulting URI is constructed from components of both URIs in the manner specified by RFC 2396, taking components from the base URI for those not specified in the original. For hierarchical URIs, the path of the original is resolved against the path of the base and then normalized. The result, for example, of resolving

sample/a/index.html#28                  (1)
against the base URI http://example.com/languages/java/ is the result URI
http://example.com/languages/java/sample/a/index.html#28
Resolving the relative URI
../../demo/b/index.html    (2)
against this result yields, in turn,
http://example.com/languages/java/demo/b/index.html
Resolution of both absolute and relative URIs, and of both absolute and relative paths in the case of hierarchical URIs, is supported. Resolving the URI file:///~calendar against any other URI simply yields the original URI, since it is absolute. Resolving the relative URI (2) above against the relative base URI (1) yields the normalized, but still relative, URI
demo/b/index.html

Relativization, finally, can be regarded as the inverse of resolution. Let u be any normalized absolute URI ending with a slash character ('/') and v be any normalized relative URI not beginning with a period character ('.') or slash character ('/'). Then, the following statement is true:

u.relativize(u.resolve(v)).equals(v)
Let u be any normalized absolute URI ending with a slash character ('/') and v be any normalized absolute URI. Then, the following statement is true:
u.resolve(u.relativize(v)).equals(v)
This operation is often useful when constructing a document containing URIs that must be made relative to the base URI of the document wherever possible. For example, relativizing the URI
http://example.com/languages/java/sample/a/index.html#28
against the base URI
http://example.com/languages/java/
yields the relative URI sample/a/index.html#28.

Character categories

RFC 2396 specifies precisely which characters are permitted in the various components of a URI reference. The following categories, most of which are taken from that specification, are used below to describe these constraints:
Describes categories alpha,digit,alphanum,unreserved,punct,reserved,escaped,and other
CategoryDescription
alpha The US-ASCII alphabetic characters, 'A' through 'Z' and 'a' through 'z'
digit The US-ASCII decimal digit characters, '0' through '9'
alphanum All alpha and digit characters
unreserved All alphanum characters together with those in the string "_-!.~'()*"
punct The characters in the string ",;:$&+="
reserved All punct characters together with those in the string "?/[]@"
escaped Escaped octets, that is, triplets consisting of the percent character ('%') followed by two hexadecimal digits ('0'-'9', 'A'-'F', and 'a'-'f')
other The Unicode characters that are not in the US-ASCII character set, are not control characters (according to the Character.isISOControl method), and are not space characters (according to the Character.isSpaceChar method)  (Deviation from RFC 2396, which is limited to US-ASCII)

The set of all legal URI characters consists of the unreserved, reserved, escaped, and other characters.

Escaped octets, quotation, encoding, and decoding

RFC 2396 allows escaped octets to appear in the user-info, path, query, and fragment components. Escaping serves two purposes in URIs: These purposes are served in this class by three related operations: These operations are exposed in the constructors and methods of this class as follows:

Identities

For any URI u, it is always the case that
new URI(u.toString()).equals(u) .
For any URI u that does not contain redundant syntax such as two slashes before an empty authority (as in file:///tmp/ ) or a colon following a host name but no port (as in http://www.example.com: ), and that does not encode characters except those that must be quoted, the following identities also hold:
    new URI(u.getScheme(),
            u.getSchemeSpecificPart(),
            u.getFragment())
    .equals(u)
in all cases,
    new URI(u.getScheme(),
            u.getAuthority(),
            u.getPath(), u.getQuery(),
            u.getFragment())
    .equals(u)
if u is hierarchical, and
    new URI(u.getScheme(),
            u.getUserInfo(), u.getHost(), u.getPort(),
            u.getPath(), u.getQuery(),
            u.getFragment())
    .equals(u)
if u is hierarchical and has either no authority or a server-based authority.

URIs, URLs, and URNs

A URI is a uniform resource identifier while a URL is a uniform resource locator. Hence every URL is a URI, abstractly speaking, but not every URI is a URL. This is because there is another subcategory of URIs, uniform resource names (URNs), which name resources but do not specify how to locate them. The mailto, news, and isbn URIs shown above are examples of URNs.

The conceptual distinction between URIs and URLs is reflected in the differences between this class and the URL class.

An instance of this class represents a URI reference in the syntactic sense defined by RFC 2396. A URI may be either absolute or relative. A URI string is parsed according to the generic syntax without regard to the scheme, if any, that it specifies. No lookup of the host, if any, is performed, and no scheme-dependent stream handler is constructed. Equality, hashing, and comparison are defined strictly in terms of the character content of the instance. In other words, a URI instance is little more than a structured string that supports the syntactic, scheme-independent operations of comparison, normalization, resolution, and relativization.

An instance of the URL class, by contrast, represents the syntactic components of a URL together with some of the information required to access the resource that it describes. A URL must be absolute, that is, it must always specify a scheme. A URL string is parsed according to its scheme. A stream handler is always established for a URL, and in fact it is impossible to create a URL instance for a scheme for which no handler is available. Equality and hashing depend upon both the scheme and the Internet address of the host, if any; comparison is not defined. In other words, a URL is a structured string that supports the syntactic operation of resolution as well as the network I/O operations of looking up the host and opening a connection to the specified resource.

API Note

Applications working with file paths and file URIs should take great care to use the appropriate methods to convert between the two. The Path#of(URI) factory method and the File#File(URI) constructor can be used to create Path or File objects from a file URI. Path#toUri() and File#toURI() can be used to create a URI from a file path. Applications should never try to construct, parse, or resolve a URI from the direct string representation of a File or Path instance.

Some components of a URL or URI, such as userinfo, may be abused to construct misleading URLs or URIs. Applications that deal with URLs or URIs should take into account the recommendations advised in RFC3986, Section 7, Security Considerations.

Author
Mark Reinhold
Since
1.4
External Specification
https://www.rfc-editor.org/info/rfc2279, https://www.rfc-editor.org/info/rfc2373, https://www.rfc-editor.org/info/rfc2396, https://www.rfc-editor.org/info/rfc2732, https://www.rfc-editor.org/info/rfc3986
See Also
RFC 2279: UTF-8, a transformation format of ISO 10646, RFC 2373: IPv6 Addressing Architecture, RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax, RFC 2732: Format for Literal IPv6 Addresses in URLs, URISyntaxException

Nested and Inner Type Summary

Modifier and TypeClass and Description
private class

Field Summary

Modifier and TypeField and Description
private transient String
private transient String
private transient String
private transient String
private transient String
private transient String
private transient String
private transient String
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private transient int
private static final char[]
private transient String
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private static final long
private transient String
private transient int
private transient String
private transient String
private transient String
pack-priv static final long
private volatile String
string

The string form of this URI.

private transient String

Constructor Summary

AccessConstructor and Description
private
URI()

public
URI(String
The string to be parsed into a URI
str
)

Constructs a URI by parsing the given string.

public
URI(String
Scheme name
scheme
,
String
User name and authorization information
userInfo
,
String
Host name
host
,
int
Port number
port
,
String
Path
path
,
String
Query
query
,
String
Fragment
fragment
)

Constructs a hierarchical URI from the given components.

public
URI(String
Scheme name
scheme
,
String
Authority
authority
,
String
Path
path
,
String
Query
query
,
String
Fragment
fragment
)

Constructs a hierarchical URI from the given components.

public
URI(String
Scheme name
scheme
,
String
Host name
host
,
String
Path
path
,
String
Fragment
fragment
)

Constructs a hierarchical URI from the given components.

public
URI(String
Scheme name
scheme
,
String
Scheme-specific part
ssp
,
String
Fragment
fragment
)

Constructs a URI from the given components.

pack-priv
URI(String scheme, String path)

Constructs a simple URI consisting of only a scheme and a pre-validated path.

Method Summary

Modifier and TypeMethod and Description
private void
appendAuthority(StringBuilder sb, String authority, String userInfo, String host, int port)

private static void
private static void
private void
private void
appendSchemeSpecificPart(StringBuilder sb, String opaquePart, String authority, String userInfo, String host, int port, String path, String query)

private static void
checkPath(String s, String scheme, String path)

private static int
private static int
public int

Returns:

A negative integer, zero, or a positive integer as this URI is less than, equal to, or greater than the given URI
compareTo
(URI
The object to which this URI is to be compared
that
)

Implements java.lang.Comparable.compareTo.

Compares this URI to another object, which must be a URI.

public static URI

Returns:

The new URI
create
(String
The string to be parsed into a URI
str
)

Creates a URI by parsing the given string.

private static int
decode(char c)

private static byte
decode(char c1, char c2)

private static String
private static String
decode(String s, boolean ignorePercentInBrackets)

private String
private static String
private static boolean
private static boolean
public boolean

Returns:

true if, and only if, the given object is a URI that is identical to this URI
equals
(Object
The object to which this object is to be compared
ob
)

Overrides java.lang.Object.equals.

Tests this URI for equality with another object.

public String

Returns:

The decoded authority component of this URI, or null if the authority is undefined
getAuthority
()

Returns the decoded authority component of this URI.

public String

Returns:

The decoded fragment component of this URI, or null if the fragment is undefined
getFragment
()

Returns the decoded fragment component of this URI.

public String

Returns:

The host component of this URI, or null if the host is undefined
getHost
()

Returns the host component of this URI.

public String

Returns:

The decoded path component of this URI, or null if the path is undefined
getPath
()

Returns the decoded path component of this URI.

public int

Returns:

The port component of this URI, or -1 if the port is undefined
getPort
()

Returns the port number of this URI.

public String

Returns:

The decoded query component of this URI, or null if the query is undefined
getQuery
()

Returns the decoded query component of this URI.

public String

Returns:

The raw authority component of this URI, or null if the authority is undefined
getRawAuthority
()

Returns the raw authority component of this URI.

public String

Returns:

The raw fragment component of this URI, or null if the fragment is undefined
getRawFragment
()

Returns the raw fragment component of this URI.

public String

Returns:

The path component of this URI, or null if the path is undefined
getRawPath
()

Returns the raw path component of this URI.

public String

Returns:

The raw query component of this URI, or null if the query is undefined
getRawQuery
()

Returns the raw query component of this URI.

public String

Returns:

The raw scheme-specific part of this URI (never null)
getRawSchemeSpecificPart
()

Returns the raw scheme-specific part of this URI.

public String

Returns:

The raw user-information component of this URI, or null if the user information is undefined
getRawUserInfo
()

Returns the raw user-information component of this URI.

public String

Returns:

The scheme component of this URI, or null if the scheme is undefined
getScheme
()

Returns the scheme component of this URI.

public String

Returns:

The decoded scheme-specific part of this URI (never null)
getSchemeSpecificPart
()

Returns the decoded scheme-specific part of this URI.

public String

Returns:

The decoded user-information component of this URI, or null if the user information is undefined
getUserInfo
()

Returns the decoded user-information component of this URI.

private static int
hash(int hash, String s)

public int

Returns:

A hash-code value for this URI
hashCode
()

Overrides java.lang.Object.hashCode.

Returns a hash-code value for this URI.

private static int
hashIgnoringCase(int hash, String s)

public boolean

Returns:

true if, and only if, this URI is absolute
isAbsolute
()

Tells whether or not this URI is absolute.

public boolean

Returns:

true if, and only if, this URI is opaque
isOpaque
()

Tells whether or not this URI is opaque.

private static int
join(char[] path, int[] segs)

private static boolean
match(char c, long lowMask, long highMask)

private static void
maybeAddLeadingDot(char[] path, int[] segs)

private static int
public URI

Returns:

A URI equivalent to this URI, but whose path is in normal form
normalize
()

Normalizes this URI's path.

private static URI
private static String
private static int
normalizedHash(int hash, String s)

public URI

Returns:

A URI whose authority field has been parsed as a server-based authority
parseServerAuthority
()

Attempts to parse this URI's authority component, if defined, into user-information, host, and port components.

private static int
percentNormalizedComparison(String s, String t, boolean testForEquality)

private static String
quote(String s, long lowMask, long highMask)

private void
readObject(ObjectInputStream
The object-input stream from which this object is being read
is
)

Reconstitutes a URI from the given serial stream.

public URI

Returns:

The resulting URI
relativize
(URI
The URI to be relativized against this URI
uri
)

Relativizes the given URI against this URI.

private static URI
relativize(URI base, URI child)

private static void
removeDots(char[] path, int[] segs)

public URI

Returns:

The resulting URI
resolve
(URI
The URI to be resolved against this URI
uri
)

Resolves the given URI against this URI.

public URI

Returns:

The resulting URI
resolve
(String
The string to be parsed into a URI
str
)

Constructs a new URI by parsing the given string and then resolving it against this URI.

private static URI
resolve(URI base, URI child)

private static String
resolvePath(String base, String child, boolean absolute)

private static void
split(char[] path, int[] segs)

public String

Returns:

The string form of this URI, encoded as needed so that it only contains characters in the US-ASCII charset
toASCIIString
()

Returns the content of this URI as a US-ASCII string.

private static int
toLower(char c)

public String

Returns:

The string form of this URI
toString
()

Overrides java.lang.Object.toString.

Returns the content of this URI as a string.

private String
toString(String scheme, String opaquePart, String authority, String userInfo, String host, int port, String path, String query, String fragment)

private static int
toUpper(char c)

public URL

Returns:

A URL constructed from this URI
toURL
()

Constructs a URL from this URI.

private static boolean
private void
writeObject(ObjectOutputStream
The object-output stream to which this object is to be written
os
)

Saves the content of this URI to the given serial stream.

Inherited from java.lang.Object:
clonefinalizegetClassnotifynotifyAllwaitwaitwait