Java Reference
In-Depth Information
Working with URLs
So far in this chapter, I have discussed sockets and datagram packets as
options for creating network applications in Java. In this section, I will show
you how to write Java programs that communicate with a URL. URL, which
stands for Uniform Resource Locator, represents a resource on the World Wide
Web, such as a Web page or FTP directory.
A URL is actually a type of URI, Uniform Resource Identifier. A URI
identifies a resource, but doesn't contain information about how to access
the resource. A URL identifies a resource and a protocol for accessing the
resource. A URI is represented in Java using the java.net.URI class.
A URL can be broken down into parts, as follows:
protocol://host:port/path?query#ref
The path is also referred to as the filename, and the host is also called the
authority. Examples of protocols include HTTP, HTTPS, FTP, and File. For
example, the following is a URL to a Web page whose protocol is HTTP:
http://www.javalicense.com/training/index.html?language=en#j2se
Notice that this URL does not specify a port, in which case the default port
for the protocol is used. With HTTP, the default port is 80.
The java.net.URL class represents a URL. The URL class has several con-
structors for creating URLs, including the following:
public URL(String protocol, String host, int port, String file) throws
MalformedURLException.
Creates a URL by putting together the
given parts.
public URL(String protocol, String host, String file) throws
MalformedURLException. Identical to the previous constructor,
except that the default port for the given protocol is used.
public URL(String url) throws MalformedURLException.
Creates a
URL from the given String.
public URL(URL context, String url) throws MalformedURLException.
Creates a URL by parsing the together the URL and String arguments.
Search WWH ::




Custom Search