Java Reference
In-Depth Information
If the protocol you need isn't supported by a particular VM, you may
be able to install a protocol handler for that scheme to enable the URL
class to speak that protocol. In practice, this is way more trouble than
it's worth. You're better off using a library that exposes a custom API
just for that protocol.
Other than verifying that it recognizes the URL scheme, Java does not check the cor‐
rectness of the URLs it constructs. The programmer is responsible for making sure that
URLs created are valid. For instance, Java does not check that the hostname in an HTTP
URL does not contain spaces or that the query string is x-www-form-URL-encoded. It
does not check that a mailto URL actually contains an email address. You can create
URLs for hosts that don't exist and for hosts that do exist but that you won't be allowed
to connect to.
Constructing a URL from a string
The simplest URL constructor just takes an absolute URL in string form as its single
argument:
public URL ( String url ) throws MalformedURLException
Like all constructors, this may only be called after the new operator, and like all URL
constructors, it can throw a MalformedURLException . The following code constructs a
URL object from a String , catching the exception that might be thrown:
try {
URL u = new URL ( "http://www.audubon.org/" );
} catch ( MalformedURLException ex ) {
System . err . println ( ex );
}
Example 5-1 is a simple program for determining which protocols a virtual machine
supports. It attempts to construct a URL object for each of 15 protocols (8 standard
protocols, 3 custom protocols for various Java APIs, and 4 undocumented protocols
used internally by Java). If the constructor succeeds, you know the protocol is supported.
Otherwise, a MalformedURLException is thrown and you know the protocol is not sup‐
ported.
Example 5-1. Which protocols does a virtual machine support?
import java.net.* ;
public class ProtocolTester {
public static void main ( String [] args ) {
// hypertext transfer protocol
testProtocol ( "http://www.adc.org" );
Search WWH ::




Custom Search