URL Connections
URL connections are closely related
to URLs, as their name implies. Indeed, you get a reference to a
URLConnection
by using the
openConnection()
method of a
URL
object; in many ways, the
URL
class is only a wrapper around the
URLConnection
class. However, URL connections
provide more control over the communication between the client and
the server. In particular, URL connections provide not just input
streams by which the client can read data from the server, but also
output streams to send data from the client to the server. This is
essential for protocols like mailto.
The java.net.URLConnection
class is an abstract
class that handles communication with different kinds of servers,
like FTP servers and web servers. Protocol-specific subclasses of
URLConnection
, hidden inside the
sun
classes, handle different kinds of servers.
Reading Data from URL Connections
URL connections take place in five steps:
The
URL
object is constructed.The
openConnection()
method of theURL
object creates theURLConnection
object.The parameters for the connection and the request properties that the client sends to the server are set up.
The
connect()
method makes the connection to the server, perhaps using a socket for a network connection or a file input stream for a local connection. The response header information is read from the server.Data is read from the connection by using the input stream returned by
getInputStream()
or through a content handler withgetContent()
. Data can be sent ...
Get Java I/O now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.