The URL Class
A URL is represented by an instance of
the java.net.URL class. A URL
object manages all the component information within a URL string and
provides methods for retrieving the object it identifies. We can
construct a URL object from a URL specification
string or from its component parts:
try {
URL aDoc =
new URL( "http://foo.bar.com/documents/homepage.html" );
URL sameDoc =
new URL("http","foo.bar.com","documents/homepage.html");
}
catch ( MalformedURLException e ) { }These two URL objects point to the same network
resource, the homepage.html document on the
server foo.bar.com. Whether the resource
actually exists and is available isn’t known until we try to
access it. At this point, the URL object just
contains data about the object’s location and how to access it.
No connection to the server has been made. We can examine the
URL’s components with
the
getProtocol( ), getHost( )
, and
getFile( ) methods. We can also compare it to
another URL with the sameFile( )
method (which has an unfortunate name for
something which may not point to a file). sameFile( ) determines whether two URLs point to the same resource.
It can be fooled, but sameFile( ) does more than
compare the URLs for equality; it takes into account the possibility
that one server may have several names, and other factors.
When
a URL is created, its specification is parsed to identify just the protocol component. If the protocol doesn’t make sense, or if Java can’t find a protocol handler for it, the URL ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access