Writing a Protocol Handler
A
URL
object uses a protocol handler to
establish a connection with a server and perform whatever protocol is
necessary to retrieve data. For example, an HTTP protocol handler
knows how to talk to an HTTP server and retrieve a document; an FTP
protocol handler knows how to talk to an FTP server and retrieve a
file. All types of URLs use protocol handlers to access their
objects. Even the lowly “file” type URLs use a special
“file” protocol handler that retrieves files from the
local filesystem. The data a protocol handler retrieves is then fed
to an appropriate content handler for interpretation.
While we refer to a protocol handler as
a single entity, it really has two parts: a
java.net.URLStreamHandler and a
java.net.URLConnection
. These are both
abstract classes that we will subclass to create
our protocol handler. (Note that these are
abstract classes, not interfaces. Although they
contain abstract methods we are required to implement, they also
contain many utility methods we can use or override.) The URL looks
up an appropriate URLStreamHandler, based on the
protocol component of the URL. The
URLStreamHandler then finishes parsing the URL and
creates a URLConnection when it’s time to
communicate with the server. The URLConnection
represents a single connection with a server, and implements the
communication protocol itself.
Locating Protocol Handlers
Protocol handlers are organized in a package hierarchy similar to content handlers. But unlike ...
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