The URL provides a reasonably intelligible form to uniquely identify or address
information on the Internet. URLs are ubiquitous; every browser uses them to identify
information on the Web. Within Java's network class library, the URL class provides a
simple, concise API to access information across the Internet using URLs.
All URLs share the same basic format, although some variation is allowed. Here are two
examples: http://www.osborne.com/ and http://www.osborne.com:80/index.htm. A URL
specification is based on four components. The first is the protocol to use, separated from
the rest of the locator by a colon (:). Common protocols are HTTP, FTP, gopher, and file,
although these days almost everything is being done via HTTP (in fact, most browsers will
proceed correctly if you leave off the "http://" from your URL specification). The second
component is the host name or IP address of the host to use; this is delimited on the left
by double slashes (//) and on the right by a slash (/) or optionally a colon (:). The third
component, the port number, is an optional parameter, delimited on the left from the host
name by a colon (:) and on the right by a slash (/). (It defaults to port 80, the predefined
HTTP port; thus, ":80" is redundant.) The fourth part is the actual file path. Most HTTP
servers will append a file named index.html or index.htm to URLs that refer directly to a
directory resource. Thus, http://www.osborne.com/ is the same as http://www.osborne.com/
index.htm.
Java's URL class has several constructors; each can throw a MalformedURLException.
One commonly used form specifies the URL with a string that is identical to what you see
displayed in a browser:
URL(String urlSpecifier) throws MalformedURLException
The next two forms of the constructor allow you to break up the URL into its component
parts:
URL(String protocolName, String hostName, int port, String path)
throws MalformedURLException
URL(String protocolName, String hostName, String path)
throws MalformedURLException
Another frequently used constructor allows you to use an existing URL as a reference
context and then create a new URL from that context. Although this sounds a little
contorted, it's really quite easy and useful.
URL(URL urlObj, String urlSpecifier) throws MalformedURLException
The following example creates a URL to Osborne's download page and then examines
its properties:
// Demonstrate URL.
import java.net.*;
class URLDemo {
public static void main(String args[]) throws MalformedURLException {
URL hp = new URL("http://www.osborne.com/downloads");
System.out.println("Protocol: " + hp.getProtocol());
System.out.println("Port: " + hp.getPort());
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home