Using a URLConnection using Java
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 theHttpURLConnection 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: " + c.getContentEncoding( ));
- System.out.println(" Content Length: " + c.getContentLength( ));
- System.out.println(" Date: " + new Date(c.getDate( )));
- System.out.println(" Last Modified: " +new Date(c.getLastModified( )));
- System.out.println(" Expiration: " + new Date(c.getExpiration( )));
-
- // If it is an HTTP connection, display some additional information.
- if (c instanceof HttpURLConnection) {
- HttpURLConnection h = (HttpURLConnection) c;
- System.out.println(" Request Method: " + h.getRequestMethod( ));
- System.out.println(" Response Message: " +h.getResponseMessage( ));
- System.out.println(" Response Code: " + h.getResponseCode( ));
- }
- }
-
- /** Create a URL, call printinfo( ) to display information about it. */
- public static void main(String[ ] args) {
- try { printinfo(new URL(args[0])); }
- catch (Exception e) {
- System.err.println(e);
- System.err.println("Usage: java GetURLInfo <url>");
- }
- }
- }


雷达卡


京公网安备 11010802022788号







