URLConnection class

The URLConnection class represents the actual connection to a resource specified by a URL. It's an abstract class whose subclasses are tailored to certain protocols as shown in the diagram:

 

A URLConnection object is returned from the URL method openConnection(). An instance of HttpURLConnection class is returned when a connection is made on a URL object that uses the HTTP protocol.  An instance of JarURLConnection represents a connection to a jar: URL. A jar: URL is a compound URL that includes the URL of a JAR archive and, optionally, a reference to a file or directory within the JAR archive.

You can download a file using the URLConnection class. This class offers more control than the simpler URL class, and allows access to more information about the resource, like content type, size, last-modified date, header fields, etc. The URLConnection connect() method performs the low-level network connection and is called by other methods that need connections (e.g., getInputStream() ). The URLConnection methods getInputStream() and getOutputStream() establish standard file streams to the object referred to by the URL. As a result, these remote URLs can be read from or written to using standard file I/O commands. .

The example illustrates the use of the URLConnection class. The openConnection() method of the URL class establishes a URLConnection object. The third line in the try block shows how to create an InputStream from the URLConnection object. Don't forget that you can get increased functionality by wrapping the InputStream in an InputStreamReader, which itself could be wrapped in a BufferedReader .


String urlAddress = “http://www.website.com/page.html”;
try{ 
	URL url = new URL(urlAddress);
	URLConnection c = url.openConnection();
	InputStream is = c.getInputStream();
	System.out.println(“Content Length:”+ c.getContentLength());		
}
catch (Exception e) {
	     System.out.println("Error: " + e);
}

Next...                                                                                                                                page 11-4