Using a URLConnection
The URLConnection
class establishes a connection to a URL. The openStream( )
method of URL
we used in Example 5-1 is merely a convenience
method that creates a URLConnection
object and calls its getInputStream(
)
method. By using a URLConnection
object directly instead of
relying on openStream( )
, you have
much more control over the process of downloading the contents of a
URL.
Example 5-2 is
a simple program that shows how to use a URLConnection
to obtain the content type,
size, last-modified date, and other information about the resource
referred to by a URL. If the URL uses the HTTP protocol, it also
demonstrates how to use the HttpURLConnection
subclass to obtain
additional information about the connection.
Note the use of the java.util.Date
class to convert a timestamp
(a long
that contains the number of
milliseconds since midnight, January 1, 1970 GMT) to a human-readable
date and time string.
Example 5-2. GetURLInfo.java
package je3.net; import java.net.*; import java.io.*; import java.util.Date; /** * A class that displays information about a URL. **/ public class GetURLInfo { /** Use the URLConnection class to get info about the URL */ public static void printinfo(URL url) throws IOException { URLConnection c = url.openConnection( ); // Get URLConnection from URL c.connect( ); // Open a connection to URL // Display some information about the URL contents System.out.println(" Content Type: " + c.getContentType( )); System.out.println(" Content Encoding: ...
Get Java Examples in a Nutshell, 3rd Edition 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.