Java Reference
In-Depth Information
• The
URI
class is purely about identification of resources and parsing of URIs. It
provides no methods to retrieve a representation of the resource identified by its
URI.
• The
URI
class is more conformant to the relevant specifications than the
URL
class.
• A
URI
object can represent a relative URI. The
URL
class absolutizes all URIs before
storing them.
In brief, a
URL
object is a representation of an application layer protocol for network
retrieval, whereas a
URI
object is purely for string parsing and manipulation. The
URI
class has no network retrieval capabilities. The
URL
class has some string parsing meth‐
ods, such as
getFile()
and
getRef()
, but many of these are broken and don't always
behave exactly as the relevant specifications say they should. Normally, you should use
the
URL
class when you want to download the content at a URL and the
URI
class when
you want to use the URL for identification rather than retrieval, for instance, to represent
an XML namespace. When you need to do both, you may convert from a
URI
to a
URL
with the
toURL()
method, and from a
URL
to a
URI
using the
toURI()
method.
Constructing a URI
URIs are built from strings. You can either pass the entire URI to the constructor in a
single string, or the individual pieces:
public
URI
(
String
uri
)
throws
URISyntaxException
public
URI
(
String
scheme
,
String
schemeSpecificPart
,
String
fragment
)
throws
URISyntaxException
public
URI
(
String
scheme
,
String
host
,
String
path
,
String
fragment
)
throws
URISyntaxException
public
URI
(
String
scheme
,
String
authority
,
String
path
,
String
query
,
String
fragment
)
throws
URISyntaxException
public
URI
(
String
scheme
,
String
userInfo
,
String
host
,
int
port
,
String
path
,
String
query
,
String
fragment
)
throws
URISyntaxException
Unlike the
URL
class, the
URI
class does not depend on an underlying protocol handler.
As long as the URI is syntactically correct, Java does not need to understand its protocol
in order to create a representative
URI
object. Thus, unlike the
URL
class, the
URI
class
can be used for new and experimental URI schemes.
The first constructor creates a new
URI
object from any convenient string. For example:
URI
voice
=
new
URI
(
"tel:+1-800-9988-9938"
);
URI
web
=
new
URI
(
"http://www.xml.com/pub/a/2003/09/17/stax.html#id=_hbc"
);
URI
book
=
new
URI
(
"urn:isbn:1-565-92870-9"
);
If the string argument does not follow URI syntax rules—for example, if the URI begins
with a colon—this constructor throws a
URISyntaxException
. This is a checked ex‐
ception, so either catch it or declare that the method where the constructor is invoked