Java Reference
In-Depth Information
Relative URLs have a number of advantages. First—and least important—they save a
little typing. More importantly, relative URLs allow a single document tree to be served
by multiple protocols: for instance, both HTTP and FTP. HTTP might be used for direct
surfing, while FTP could be used for mirroring the site. Most importantly of all, relative
URLs allow entire trees of documents to be moved or copied from one site to another
without breaking all the internal links.
The URL Class
The java.net.URL class is an abstraction of a Uniform Resource Locator such as http://
www.lolcats.com/ or ftp://ftp.redhat.com/pub/ . It extends java.lang.Object , and it is a
final class that cannot be subclassed. Rather than relying on inheritance to configure
instances for different kinds of URLs, it uses the strategy design pattern. Protocol han‐
dlers are the strategies, and the URL class itself forms the context through which the
different strategies are selected.
Although storing a URL as a string would be trivial, it is helpful to think of URLs as
objects with fields that include the scheme (a.k.a. the protocol), hostname, port, path,
query string, and fragment identifier (a.k.a. the ref ), each of which may be set inde‐
pendently. Indeed, this is almost exactly how the java.net.URL class is organized,
though the details vary a little between different versions of Java.
URLs are immutable. After a URL object has been constructed, its fields do not change.
This has the side effect of making them thread safe.
Creating New URLs
Unlike the InetAddress objects in Chapter 4 , you can construct instances of
java.net.URL . The constructors differ in the information they require:
public URL ( String url ) throws MalformedURLException
public URL ( String protocol , String hostname , String file )
throws MalformedURLException
public URL ( String protocol , String host , int port , String file )
throws MalformedURLException
public URL ( URL base , String relative ) throws MalformedURLException
Which constructor you use depends on the information you have and the form it's in.
All these constructors throw a MalformedURLException if you try to create a URL for an
unsupported protocol or if the URL is syntactically incorrect.
Exactly which protocols are supported is implementation dependent. The only proto‐
cols that have been available in all virtual machines are http and file, and the latter is
notoriously flaky. Today, Java also supports the https, jar, and ftp protocols. Some virtual
machines support mailto and gopher as well as some custom protocols like doc, netdoc,
systemresource, and verbatim used internally by Java.
Search WWH ::




Custom Search