O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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:

  1. The URL object is constructed.

  2. The openConnection() method of the URL object creates the URLConnection object.

  3. The parameters for the connection and the request properties that the client sends to the server are set up.

  4. 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.

  5. Data is read from the connection by using the input stream returned by getInputStream() or through a content handler with getContent(). Data can be sent ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required