USING THE URLCONNECTION CLASS

Một phần của tài liệu sams java distributed objects (Trang 309 - 314)

Recall that the URL class, which you met in Chapter 13, “Sockets,” lets you download the document identified by a URL. Its cousin class URLConnection provides access to many attributes that describe the document and the server response that provided it. You don’t use a constructor to obtain an instance of URLConnection ; instead, you use the openConnection method of the URL class. Once you have a URLConnection instance, you can invoke any of the methods summarized in Table 18.1. The

getHeaderField method returns the value of a specified field of the server’s response header. Table 18.2 describes the most commonly used fields.

TABLE 18.1 KEY METHODS OF THE URLConnection CLASS

Method Function

Object

getContent() Returns an object that represents the contents of the document associated with the URLConnection, if an appropriate content handler is available.

String getContentEncoding() Returns a String that describes the type of encoding used by the document associated with the

URLConnection.

int

getContentLength()

Returns the length (in bytes) of the document associated with the URLConnection.

String

getContentType() Returns a String that describes the type of encoding used by the document associated with the

URLConnection.

long getDate() Returns a long that holds the creation date and time of the server’s response.

long

getExpiration() Returns a long that holds the expiration date and time of the server’s response.

String

getHeaderField(String name )

Returns a String that holds the value of the specified field of the response header returned by the server. (See Table 18.2 for the names of the response header fields.)

String

getHeaderField(int n)

Returns a String that holds the value of the specified field of the response header returned by the server.

Response header fields are numbered beginning with 0.

long

getIfModifiedSince() Returns a long that holds the modification date and time that force refetching of the document associated with the URLConnection .

InputStream

getInputStream() Returns an InputStream that contains the bytes of the document associated with the URLConnection.

long

getLastModified() Returns a long that holds the date and time at which the document associated with the URLConnection was last modified.

TABLE 18.2 KEY SERVER RESPONSE HEADER FIELDS

Field Meaning

Allowed The request methods (for example, GET , PUT , and POST ) that the user can issue for this URL

Content-Encoding The type of encoding of the response message (for example, x-zip-compressed)

Content-Language The language of the response message

Content-Length The length (in bytes) of the response message

Content-Transfer-

Encoding The type of encoding used for MIME messages

Content-Type The MIME type and subtype of the content of this message (for example, text/plain)

Cost The cost of retrieving the document

Date The creation time (GMT) of the document

Derived-From The version of the document from which this document derives

Expires The time (GMT) at which the document expires and should be refetched

Last-Modified The time (GMT) at which the document was last modified Message-ID A unique identifier for this message

Public The request methods anyone can issue for this URL

Title The title of this document

URI The URI (Universal Resource Identifier; for practical purposes, the term is synonymous with URL) or URL of the document

Version The version of the document

WWW-Authenticate The authorization method used by the server

WWW-Link The HTML link reference of the document

Figure 18.1 shows the output of WebClient, a simple applet that uses the URL and URLConnection classes to download a Web page and its description. The applet doesn’t render the HTML contents of the document, it merely displays them. To operate the applet, you merely type a URL in the text box and press Enter. Let’s see how the applet works.

Figure 18.1: The WebClient applet displays the attributes and content of a Web document.

Listing 18.1 shows the source code of the WebClient applet, except for the inner class URLHandler, which provides an actionPerformed method that handles

ActionEvents associated with the TextField used to input a URL. The main point of interest is the array theHeaders, which contains the names of the response field headers the applet retrieves. Otherwise, most of the code is user interface oriented.

LISTING 18.1 WebClient.java —AN APPLET THAT DISPLAYS WEB DOCUMENT CONTENTS AND CHARACTERISTICS

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.net.*;

import java.util.Date;

public class WebClient extends Applet {

TextField theURL = new TextField(32);

TextArea theData = new TextArea(6, 64);

TextArea theContent = new TextArea(10, 64);

String [] theHeaders = { "Allowed",

"Content-Encoding", "Content-Language", "Content-Length",

"Content-Transfer-Encoding", "Content-Type",

"Cost", "Date",

"Derived-From", "Expires",

"Last-Modified", "Message-ID", "Public", "Title", "URI", "Version",

"WWW-Authenticate", "WWW-Link",

};

public void init() {

Font f = new Font("Monospaced", Font.PLAIN, 12);

setFont(f);

Panel p1 = new Panel();

Panel p2 = new Panel();

setLayout(new BorderLayout());

add(p1, BorderLayout.NORTH);

add(p2, BorderLayout.CENTER);

p1.setLayout(new GridLayout(0, 1));

p1.add(new Label("URL:"));

p1.add(theURL);

p2.setLayout(new GridLayout(0, 1));

Panel p3 = new Panel();

Panel p4 = new Panel();

p2.add(p3);

p2.add(p4);

p3.setLayout(new BorderLayout());

p3.add(new Label("URL Data:"), BorderLayout.NORTH);

p3.add(theData, BorderLayout.CENTER);

p4.setLayout(new BorderLayout());

p4.add(new Label("URL Content:"), BorderLayout.NORTH);

p4.add(theContent, BorderLayout.CENTER);

theURL.addActionListener(new URLHandler());

theData.setEditable(false);

theContent.setEditable(false);

}

public void println(String s) {

theData.append(s + "\n");

}

public void fatalError(Exception ex) {

ex.printStackTrace();

}

// Inner class omitted }

Listing 18.2 shows the URLHandler inner class of the WebClient class. The actionPerformed method retrieves and displays the document contents and

characteristics. To do so, it constructs a URL using the text input by the user. It invokes the openConnection method to obtain a URLConnection and calls several

URLConnection methods that provide document characteristics. It uses a simple for loop to obtain and display the response header fields. It displays the document

characteristics in the upper TextArea, theData, by using the println method of its enclosing class.

LISTING 18.2 WebClient.java — INNER CLASS

class URLHandler implements ActionListener {

public void actionPerformed(ActionEvent evt) {

try {

theData.setText("");

theContent.setText("");

URL url = new URL(theURL.getText());

URLConnection connect = url.openConnection();

println("Content Encoding: " + connect.getContentEncoding());

println("Length: " +

connect.getContentLength());

println("Type: " +

connect.getContentType());

println("Date: " +

new Date(connect.getDate()));

println("Expiration: " +

new Date(connect.getExpiration()));

println("Last Modified: " +

new Date(connect.getLastModified()));

for (int i = 0; i < theHeaders.length; i++) {

String header =

connect.getHeaderField(theHeaders[i]);

println(theHeaders[i] + ": " + header);

}

BufferedReader in = new BufferedReader(

new InputStreamReader(

url.openStream()));

String line;

while ((line = in.readLine()) != null) {

theContent.append(line + "\n");

}

in.close();

}

catch (Exception ex) { fatalError(ex); } }

}

To obtain the document contents, the actionPerformed method uses the URL.openStream method. It wraps the returned InputStream reader within a BufferedReader , which provides the convenient readLine method for reading the stream one line at a time. The method simply appends each line of input to the lower TextArea, theContent.

Generally, your programs will need to access only a few (if any) document characteristics.

Therefore, your programs using URLConnection and URL to access a document won’t usually be this long. Notice that you can download the contents of a URL with less than a dozen lines of code. URL is simple to use, but powerful.

Một phần của tài liệu sams java distributed objects (Trang 309 - 314)

Tải bản đầy đủ (PDF)

(693 trang)