Scrigroup - Documente si articole

     

HomeDocumenteUploadResurseAlte limbi doc
AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows
WordXml

AspAutocadCDot netExcelFox proHtmlJava
LinuxMathcadPhotoshopPhpSqlVisual studioWindowsXml

Handling URLs And Networking Exceptions

java



+ Font mai mare | - Font mai mic



Handling URLs And Networking Exceptions

If you are developing Java applications for the World Wide Web, this chapter will help you start writing Java applets that will navigate the Web. It introduces you to some of the basic concepts of the World Wide Web and explains, in detail, the Java classes that help you tap into the resources on the Web from within a Java application. In addition, it describes the exception signals that are thrown when an error is detected while connecting to or using a resource available over the network. The chapter project illustrates how you can use the Java classes to access objects specified by Uniform Resource Locator addresses. This will help you get started with writing your own Java programs that interact with the Internet.



URLs, Protocols, and MIME

As its name indicates, the World Wide Web is a global network of computers. Web clients request and receive information from Web servers. Just as in postal addresses in different countries, the location of information may vary from one computer to another. If each computer had its own addressing scheme for retrieving its data, then the process of transparently accessing this information would become very difficult. The architects of the Web formulated an addressing scheme that could be used by one and all to serve and access information on the Web. Information on this network is accessible using an address specification called a URL. URL stands for Uniform Resource Locator. It is a structured address that uniquely identifies a resource (be it a document, an image, or whatever) on the World Wide Web.

A complete URL consists of a protocol specifier followed by a string, whose format depends on the protocol specification. Many protocols are supported on the World Wide Web, the most popular being the HTTP or HyperText Transfer Protocol. Other popular protocols are news (to read Usenet newsgroups), gopher (the Gopher protocol) and many more. The client-server interaction is markedly different among the various protocols. The basic syntax of a HTTP URL is as follows:

https://hostname[:portnumber]/directory/filename

The http denotes the protocol type. Colons and slashes (/) are used as delimiters. The hostname field is used to specify an Internet hostname (e.g., www.syr.edu). The portnumber is an optional field that is used to specify the port on the target host, at which an http server is running. If it is omitted then the default port for the protocol is used. The directory and file name fields are used to specify the path name of the document that is to be retrieved. This path name is relative to the directory that the http server makes public. Figure 11-1 looks at an example of an HTTP Uniform Resource Locator in detail.


Figure 11-1  Anatomy of a HyperText Transfer Protocol (HTTP) URL

World Wide Web browsers have become very popular. Information that is out there on the Internet is just a click of the mouse button away. How does the browser distinguish between image files, text files, audio files, and the many other file formats that exist? Part of the protocol between the client and the server involves sending some header or context information about the data that is being sent by the server. The Multipurpose Internet Mail Extensions (MIME) format specifies this context information. A MIME type is of the format:

type/subtype.

Using this information, the client (browser) can identify the type of file that it retrieved. The major types supported on the World Wide Web are: text, image, audio, video, and application. Even among these major types of files there are different formats. For example, two popular data formats for image files are GIF (Graphics Interchange Format) and TIFF (Tagged Image File Format). The subtype of the MIME-type specifies the exact format of the file. This table lists some sample content types and their corresponding MIME-types:


Content Type

MIME-Type/Subtype


GIF image

image/gif

TIFF image

image/tiff

Plain text file

text/plain

HTML file

text/html

Audio file (AU format)

audio/basic


Java and the World Wide Web

Java provides many classes that can be used to write applications that access resources on the World Wide Web. The URL class encapsulates the concept of a Uniform Resource Locator. The URL class and the Applet class will satisfy most of the needs of Java Web applications. The designers of the Java Development Kit included a set of extensible classes that are very useful for programmers who are developing Web browsers and for those involved in developing protocols to be used on the Web.

Each protocol has its own set of specifications for client-server interaction. If you want to write your own protocol handler in Java, you must extend and implement a number of classes. The first of these is the URLStreamHandler class. This class must be extended to implement the protocol-specific functionality. The URLConnection class represents a connection to an object referenced by a URL. The implementation of this class also is protocol-specific. It is this class that determines what type of content is in the file referenced by the URL.

For each type of file format, (such as GIF or HTML) there is an associated MIME-type/subtype combination. The ContentHandler class must be extended for each MIME-type. Figure 11-2 shows the basic relationships between URLs, ProtocolHandlers, and ContentHandlers.


Figure 11-2  URL class relationships

The basic functionality required of a ContentHandler is very small. A ContentHandler object should be able to read data off a URLConnection and construct an object that represents that content type. So if there is a subclass of Image that represents a GIF image, a ContentHandler for GIF files would simply read the data off the URLConnection and return a GIFImage object.

The URLStreamHandlerFactory and ContentHandlerFactory interfaces may be implemented so that the protocol-specific and content-specific classes can be constructed within the factory object. This provides a simple, uniform interface that the Java classes use to manufacture different protocol-specific or content-specific classes without explicitly specifying the class name. All these classes and interfaces provide a useful abstraction for developers of applications, such as Web browsers. ContentHandlers provide a means by which even nonstandard data formats can be viewed without having a viewer installed on your local machine. Using Java, you get the viewer bundled along with the data!

Implementing a protocol handler or a content handler is highly specific to the nature of the protocol or the format of the data and is beyond the scope of this book. As a consequence, some of the method descriptions are not accompanied by concrete examples. The HotJava browser uses implementations of protocol and content handlers written in Java. If you develop a protocol handler or a content handler, you will need to refer to the browser's documentation to determine the naming policy for these classes and also to determine where these classes must be installed so that the browser uses your protocol and content handlers.

URL and Networking Exception Summaries

Exceptions signal abnormal error conditions within the application. In object-oriented terminology, a method that detects an error may throw (or generate) an exception. In order to detect this error condition, the application that invoked the method must catch the exception. The Java keywords try and catch are used to detect exceptions. Exceptions are usually caught to inform the user that something bad happened. Exceptions related to URLs and networking are described at the end of the summary section.

Table 11-1 summarizes the classes and interfaces described in this chapter.

Table 11-1 Class/interface descriptions


Class/Interface

Description


ContentHandler

Interprets data read from a URLConnection object, and constructs an object that represents a specific MIME-type/subtype combination, such as image/gif, text/plain, etc.

ContentHandlerFactory

Defines the interface that must be implemented by classes that know how to create an instance of the subclass of ContentHandler that handles the specified MIME-type.

URL

Represents a Uniform Resource Locator (URL). Uniform Resource Locators are references to objects on the World Wide Web that can be retrieved by using protocols such as the HyperText Transfer Protocol (HTTP).

URLConnection

Sets or modifies the connection-session parameters and handles the network connection to the remote object that is referred to by a Uniform Resource Locator.

URLEncoder

Encodes strings into URL format. Encoding the strings in this uniform format ensures that the string is not corrupted by errors, such as character set variations on different systems (when transmitted over the network).

URLStreamHandler

Specifies an abstract base class that must be subclassed to implement stream handlers for specific protocols, such as http, nntp, ftp, etc.

URLStreamHandlerFactory

Defines the interface that must be implemented by a class that knows how to create an instance of a specific subclass of URLStreamHandler that handles a protocol.

MalformedURLException

Signals that the specified Uniform Resource Locator (URL) is invalid.

ProtocolException

Indicates that an EPROTO error was detected when the application tried to connect to a socket.

SocketException

Indicates that an error occurred while performing an operation on a socket.

UnknownHostException

Indicates that the address of the host specified by a network client is not valid.

UnknownServiceException

Signals an error indicating that the requested service is not supported by the client-server protocol.

ContentHandler

Purpose

To interpret data read from a URLConnection object and construct an object that represents a specific MIME-type/subtype combination, such as image/gif, text/plain, and so on.

Syntax

public class ContentHandler extends Object

Description

This abstract class must be subclassed to implement content handlers for specific MIME-type/subtype combinations. ContentHandlers read data from the URLConnection stream and construct an object that represents the MIME-type. Subclasses of this class can be used in Web browsers to interpret specific MIME-type/subtype combinations. Figure 11-2 shows the basic relationships between URLs, ProtocolHandlers and ContentHandlers. Applications should not construct ContentHandlers directly. Instead, they should use the getContent methods of the URL class or the URLConnection class. This method constructs and returns an instance of a ContentHandler object that is appropriate for the MIME-type of the connection. By default, the URLConnection class combines the MIME-type and subtype to form a path name for the Java class. It then looks for a Java .class file of this name in the sun/net/www/content directory (if such a directory is found relative to the directory in which the standard Java classes were installed). For example, if the MIME-type/sub-type returned were image/gif, the default content handler for this object would be sun/net/www/content/image/gif.class. Figure 11-3 shows the inheritance diagram for the ContentHandler class.


Figure 11-3  Inheritance diagram for the ContentHandler class

PackageName

java.net

Imports

import java.net.ContentHandler;

Constructors

public ContentHandler()

Parameters

None.

Example

The following example shows how you can write your own content handlers.

// File: tdif.java
A Java class that represents an image that conforms to a
fictitious image format known
as Three D Image Format. Files of this type will have the
.tdi extension
[Note: This class is not complete]
package CustomPackage;
import java.awt.Image;
import java.net.*;
import java.io.*;
public class tdif extends Image catch (IOException e)
}
// Implementation of the various methods of the Image
class are added here
..


// File: tdi.java ContentHandler class for image/tdi objects
For the purposes of this example, assume that the
MIME-type/subtype combination for objects of
Three D Image Format are image/tdi.
Thus, any objects of this format will be handled by the
sun/net/www/content/image/tdi.class
content handler class. This class just creates and returns
a tdif object.

package sun.net.www.content.image;
import CustomPackage.tdif;

public class tdi extends ContentHandler

getContent(URLConnection)

ClassName

ContentHandler

Purpose

Reads and interprets the data from a URLConnection stream and constructs an object that represents the MIME-type/subtype combination handled by this class.

Syntax

public abstract Object getContent(URLConnection urlc) throws IOException

Parameters

urlc

The URLConnection stream from which data must be read and interpreted to create an object for the MIME-type that this class represents.

Description

This abstract method must be implemented by each subclass of ContentHandler to read and interpret data from the URLConnection data-stream and create a representation of the MIME object that the subclass represents. An IOException is thrown if some error occurs while reading the data from the URLConnection stream.

Imports

import java.net.ContentHandler;

Returns

This method returns an Object that represents the specific MIME-type/subtype implemented by this class.

See Also

The getContent method of the URL class and the getContent of the URLConnection class described in this chapter

Example

The previous example illustrates how you can implement this method in your own content handlers.

ContentHandlerFactory

Purpose

Defines the interface that must be implemented by classes that know how to create an instance of a subclass of ContentHandler that handles a specified MIME-type.

Syntax

public interface ContentHandlerFactory extends Object

Description

As the name implies, a class that implements this interface must know how to manufacture (construct) instances of subclasses of the ContentHandler class. Each concrete subclass of the abstract base class, ContentHandler, handles a specific MIME-type. A class that implements this interface must maintain an association between the MIME-type strings and the name of the class that handles that MIME-type/subtype combination. ContentHandlerFactory objects construct (on demand) the appropriate ContentHandler for a given MIME-type. This class will mainly be used in subclasses of the URLConnection class. If you are writing content handlers and you do not want to install these classes in the default directories, such as sun/net/www/content/, then you can use a class that implements the ContentHandlerFactory interface to create instances of your classes. To implement a protocol handler in Java, you must extend the URLStreamHandler class to provide implementations of streams that are specific to the protocol. You must also subclass the URLConnection class to provide implementations of the different types of content that can be handled by the protocol. The URLConnection class has a static ContentHandlerFactory object as a member variable. This implies that every instance of the URLConnection class uses the same source for constructing ContentHandlers. Figure 11-4 shows the inheritance diagram for the ContentHandlerFactory interface.


Figure 11-4  Inheritance diagram for the ContentHandlerFactory interface

PackageName

java.net

Imports

import java.net.ContentHandlerFactory;

Constructors

None.

Parameters

None.

Example

The example for the createContentHandler method illustrates how you can implement a custom Content Handler factory class.

createContentHandler(String)

InterfaceName

ContentHandlerFactory

Purpose

Constructs an instance of the specific subclass of ContentHandler that handles the specified MIME-type.

Syntax

public abstract ContentHandler createContentHandler(String mimetype)

Parameters

mimetype

The Multipurpose Internet Mail Extension (MIME) type for which an instance of the appropriate subclass of ContentHandler is to be constructed.

Description

Classes that implement the ContentHandlerFactory interface must know the names and locations of the specific subclasses of ContentHandler that handle the various MIME-type/subtype combinations. Depending on the MIME-type/subtype specified, an instance of the appropriate subclass of ContentHandler is constructed and returned. How does the URLConnection class know which MIME-type is to be supplied as a parameter to this method? The getContentType method of the URLConnection class provides the answer to this question. The getContentType method returns a string that contains the MIME-type/subtype combination of the URLConnection. This string can then be used as the parameter to this method.

Imports

import java.net.ConentHandlerFactory;

Returns

This method returns an instance of the ContentHandler subclass that represents the specified MIME-type.

See Also

The ContentHandler class; the setContentHandlerFactory method of the URLConnection class; and the getContentType method of the URLConnection class, all of which are described in this chapter

Example

The following example shows you a class that implements this interface.

// File: CustomContentHandlerFactory.java
A Java class that implements the ContentHandlerFactory interface
This factory looks for classes in the CustomPackage/content
directory
It constructs the class name by prepending this "root" directory
to the
MIME-type/sub-type of the object

package CustomPackage;
import java.net.*;

public class CustomContentHandlerFactory implements ContentHandlerFactory


URL

Purpose

Represents a Uniform Resource Locator (URL). Uniform Resource Locators are references to objects on the World Wide Web that can be retrieved using protocols such as the HyperText Transfer Protocol (HTTP).

Syntax

public final class URL extends Object

Description

This class is used to access objects on the World Wide Web. It encapsulates the concept of a Uniform Resource Locator. Handling the different protocol types (http, ftp) and content types (GIF images, Postscript files) is transparent to the application that uses URL objects to access data on the Web. This class cannot be subclassed, and once constructed, the URL object cannot be modified (i.e., instances of the URL class are constant objects). You can create URL objects either by specifying the absolute path or by specifying a path relative to another URL. Constructing URL objects by specifying a path relative to another URL object is useful for creating URLs to references (named anchor tags, e.g., "https://www.syr.edu/index.html#LIBRARY") within a HTML (HyperText Markup Language) file. If the parameters supplied to the constructor are not valid, a MalformedURLException is generated, and hence the constructor statements should be within a try/catch statement pair. The URL class maintains a table of URLStreamHandler objects that handle different protocols such as http, file, news, doc, and verbatim. These URLStreamHandler objects are created on demand and are shared by all instances of the URL class (i.e., the table is a static member variable of the URL class). When a URL object is created, a URLStreamHandler object is created. This specific instance of the URLStreamHandler object depends on the protocol specified in the URL. Figure 11-2 shows the basic relationships between URLs, ProtocolHandlers, and ContentHandlers. If a URLStreamHandler factory object has been defined, then this factory is used to generate the URLStreamHandler. If no factory has been defined, then the URL class looks in certain default directories (for example: sun/net/www/protocol/http/Handler.class for the http protocol) for the URLStreamHandler subclass that implements the specified protocol. If you are writing Java applications that access resources on the World Wide Web, then you will be using the URL class often. Figure 11-5 shows the inheritance diagram for the URL class.


Figure 11-5  Inheritance diagram for the URL class

PackageName

java.net

Imports

import java.net.URL;

Constructors

public URL(String protocol, String host, int port, String file) throws MalformedURLException

public URL(String protocol, String host, String file) throws MalformedURLException

public URL(String spec) throws MalformedURLException

public URL(URL context, String spec) throws MalformedURLException

Parameters

protocol

The protocol (http, news, and so on) to use for this URL.

host

The Internet name of the host machine to connect to (e.g., www.syr.edu).

port

The port number on the host machine to connect to.

file

The path name of the file on the host.

spec

A string specifying an absolute (unparsed) URL (e.g. "https://www.syr.edu/").

context

A URL object to be used as a context into which a string specifying a URL (usually a relative path to the context URL) may be parsed.

Example

The following samples of code illustrate the different ways of constructing URL objects. Refer to the URLTestControls constructor method in Step 7 of the project at the end of this chapter for a more complete example.


try catch (MalformedURLException e)

equals(Object)

ClassName

URL

Purpose

Compares the specified URL object to the URL on which this method is invoked and determines whether the two URL objects are equal or not.

Syntax

public boolean equals(Object obj)

Parameters

obj

The URL object to compare against.

Description

The URL object specified in the parameter of this method is compared to the URL object on which the method was invoked. The protocol, hostname, port number, and file specifications of two URL objects are compared.

Note: This method does not make use of facilities like the Unix Domain Name Service (DNS) to look for aliases of the hostnames. It simply compares the strings specifying the hostname, protocol, and file specifications. If the hostname strings do not match, this method evaluates the Internet addresses of the hostnames of the URL objects being compared.

Imports

import java.net.URL;

Returns

This method returns true if and only if the parameter obj is an instance of the URL class and the protocol, host, port, and file properties of the two URL objects match.

Example

The following Java class illustrates the use of this method.

import java.net.*;

public class URLEqualsTest catch (MalformedURLException e)
}

getContent()

ClassName

URL

Purpose

Returns an object constructed from the data read from the object referred to by this URL.

Syntax

public final Object getContent() throws IOException

Parameters

None.

Description

The protocol-specific URLStreamHandler handling this URL determines the content type of the object referred to by this URL. The ContentHandler for that MIME-type reads the data from the URLConnection stream and constructs the content-specific object that is returned.

Imports

import java.net.URL;

Returns

The Object returned by this method is constructed from the data read from the URLConnection. Depending on the MIME-type of the object referred to by this URL, a specific instance of a class that represents that content is created. The instance of operator should be used to determine the class that this object belongs to. An IOException indicates that an error occurred while reading and interpreting data from the remote object.

See Also

The ContentHandler class; the getContent method; and the URLConnection class, described in this chapter

Example

The following example shows how you can use the instance of operator to determine the type of object that the URL refers to.

// File: URLContentType.java

import java.net.*;
import java.io.IOException;

public class URLContentType

} catch (IOException ie)
} catch (MalformedURLException e)
}

This program prints the following on the screen:

This URL refers to a String object
Contents of the URL object: This is the only line of text in hello.txt!

getFile()

ClassName

URL

Purpose

Gets the filename portion of the URL specification.

Syntax

public String getFile()

Parameters

None.

Description

This method returns the value of the filename portion of the URL specification. The first two forms of the URL constructor allow you to specify the filename explicitly. The next two variants of the URL constructor allow you to specify a URL as a string of text (e.g., "https://www.syr.edu/index.html") and the URL constructor parses this string to extract the filename ("/index.html" in this case).

Imports

import java.net.URL;

Returns

The return value of this method is a String object that contains the name of the file referenced by this URL object.

See Also

Constructors for this class

Example

Refer to the showParams() method in the URLPanel class of the section project (Step 5) at the end of this chapter.

getHost()

ClassName

URL

Purpose

Retrieves the hostname portion of the Uniform Resource Locator specification.

Syntax

public String getHost()

Parameters

None.

Description

This method returns the value of the hostname portion of the URL specification. The first two forms of the URL constructor allow you to specify the hostname explicitly. The next two variants of the URL constructor allow you to specify a URL as a string of text (e.g., "https://www.syr.edu/index.html") and the URL constructor parses this string to extract the hostname ("www.syr.edu" in this case).

Imports

import java.net.URL;

Returns

The return value of this method is a String object that contains the hostname on which the file referenced by this URL object resides.

See Also

Constructors for this class

Example

This use of this method is illustrated in the showParams() method in the URLPanel class of the section project (Step 5) at the end of this chapter.

getPort()

ClassName

URL

Purpose

Gets the port number (on the target host machine) to which this URL object connects.

Syntax

public int getPort()

Parameters

None.

Description

This method returns the value of the port number of the URL specification. The first form of the URL constructor allows you to explicitly specify the port number. The second form of the URL constructor sets the port number to the default value (which depends on the protocol). The next two variants of the URL constructor allow you to specify a URL as a string of text (e.g., "https://www.syr.edu:80/index.html") in which you can optionally specify a port number, and the URL constructor parses this string to extract the port number (80 in this case).

Imports

import java.net.URL;

Returns

This method returns an integer that specifies the port number this URL object connects to. If the port number was not explicitly specified while constructing the URL, then the return value of this method is -1.

See Also

Constructors for this class

Example

The use of this method is illustrated in the showParams() method in the URLPanel class of the section project (Step 5) at the end of this chapter.

getProtocol()

ClassName

URL

Purpose

Gets the protocol used to retrieve the object referenced by this URL.

Syntax

public String getProtocol()

Parameters

None.

Description

This method returns the value of the protocol portion of the URL specification. The first two forms of the URL constructor allow you to specify the protocol explicitly. The next two variants of the URL constructor allow you to specify a URL as a string of text (e.g., "https://www.syr.edu/index.html") and the URL constructor parses this string to extract the protocol ("http" in this case).

Imports

import java.net.URL;

Returns

The return value of this method is a String object that specifies the protocol used to retrieve the object referenced by this URL.

See Also

Constructors for this class

Example

The use of this method is illustrated in the showParams() method in the URLPanel class of the section project (Step 5) at the end of this chapter.

getRef()

ClassName

URL

Purpose

Gets the anchor tagname for this URL object. Anchors are used to point to a specific section in a document.

Syntax

public String getRef()

Parameters

None

Description

The # mark indicates a named anchor in a HTML (HyperText Markup Language) document. By specifying an anchor in a document, one can go directly to that specified section in the document. This method retrieves the name of the anchor (if any) from the URL specification.

Note: This method does not detect the reference specification when the URL object is created using the following form of the URL constructor.

URL u1 = new URL("https://www.syr.edu/index.html#LIBRARY");

In this case, u1.getRef() returns the null string.

Imports

import java.net.URL;

Returns

This method returns the anchor tagname (string following the '#' character) in the URL.

See Also

The set method of this class and the different forms of constructors for this class

Example

The use of this method is illustrated in the showParams() method in the URLPanel class of the section project (Step 5) at the end of this chapter.

hashCode()

ClassName

URL

Purpose

Returns a hash value that can be used to index into a hash table.

Syntax

public int hashCode()

Parameters

None.

Description

This method overrides the hashCode method of the Object class. It returns a number that is the hash value of the URL object on which this method was invoked.

Imports

import java.net.URL;

Returns

This method returns an integer that represents the hash value for this URL object.

Example

The following Java class shows how to invoke this method in your application.

import java.net.*;

public class URLHashTest catch (MalformedURLException e)
}

openConnection()

ClassName

URL

Purpose

Opens a connection to the object referred to by this URL object.

Syntax

public URLConnection openConnection() throws IOException

Parameters

None.

Description

The subclass of URLStreamHandler that handles the protocol specified by this URL object creates an instance of a subclass of the URLConnection class and returns this URLConnection object. The specific subclass of the URLConnection class to instantiate is determined by the URLStreamHandler object that implements the protocol used by this URL object. An IOException is thrown when there is an error in establishing a connection to the remote object.

Imports

import java.net.URL;

Returns

This method returns an instance of the protocol-specific subclass of the URLConnection class that contains a connection to the object referred to by this URL.

See Also

The URLConnection class; the openStream and getContent methods of the URL class, described in this chapter

Example

This example illustrates how you can access the URLConnection object associated with a URL and read data from the URLConnection object over the network.

// File: URLRead1.java
A class that reads data from a URL using a URLConnection object

import java.net.*;
import java.io.*;

public class URLRead1
data.close(); // close
the input stream
}

} catch (IOException ie)
} catch (MalformedURLException e)
}

The file test.html contains:

<HTML>
<HEAD>
<TITLE> A Sample HTML file </TITLE>
</HEAD>
<BODY>
<P> This is the first and only paragraph in this file. This file
contains 10 lines.
</BODY>
</HTML>

This example prints the following lines on the screen:

Line 1: <HTML>
Line 2: <HEAD>
Line 3: <TITLE> A Sample HTML file </TITLE>
Line 4: </HEAD>
Line 5: <BODY>
Line 6: <P>
Line 7: This is the first and only paragraph in this file. This file
Line 8: contains 10 lines.
Line 9: </BODY>
Line 10: </HTML>

openStream()

ClassName

URL

Purpose

Opens an input stream to the object referenced by this URL.

Syntax

public final InputStream openStream() throws IOException

Parameters

None.

Description

This function returns an InputStream to the object referred to by the URL. The InputStream is established by the protocol-specific URLConnection object that was created by the URLStreamHandler object handling this URL. If the protocol of this URL object supports input streams, then applications can use this InputStream object to read the data of the object referred to by the URL.

Imports

import java.net.URL;

Returns

The InputStream object returned by this method can be used to read the data of the object referred to by this URL object. If the protocol does not support InputStreams, an UnknownServiceException is thrown. Protocol implementors can trigger other exceptions while implementing the getInputStream method of the protocol-specific subclass of the URLConnection class.

See Also

The getInputStream method of the URLConnection class; the openConnection and getContent methods of the URL class described in this chapter

Example

This example essentially performs the same function as the previous example. It uses the openStream method of the URL class to read data from the object. This example uses the same test.html file as the previous example.

// File: URLRead2.java
A class that reads data from a URL using the URL's
openStream method

import java.net.*;
import java.io.*;

public class URLRead2
data.close(); // close the input
stream

} catch (IOException ie)
} catch (MalformedURLException e)
}

When executed, this example prints the following lines on the screen:

Line 1: <HTML>
Line 2: <HEAD>
Line 3: <TITLE> A Sample HTML file </TITLE>
Line 4: </HEAD>
Line 5: <BODY>
Line 6: <P>
Line 7: This is the first and only paragraph in this file. This file
Line 8: contains 10 lines.
Line 9: </BODY>
Line 10: </HTML>

sameFile()

ClassName

URL

Purpose

Compares the specified URL object against the object on which this method was invoked.

Syntax

public boolean sameFile(URL other)

Parameters

other

The URL object that must be compared against the object on which this method is invoked.

Description

If the four fields ( protocol, hostname, port number, and file path name) of the two URL objects are the same, then the URLs are said to be equal. The reference field, that indicates an offset in a file, is not taken into account for the comparison.

Imports

java.net.URL;

Returns

This method returns true if the specified URL object is equal to this URL; otherwise, it returns the boolean value false.

See Also

The equals and set methods of the URL class, described in this chapter

Example

This method is used in the example for the equals method of this class.

set(String, String, int, String, String)

ClassName

URL

Purpose

Sets the individual fields of the URL object. This is a privileged function that is accessible only to classes in the java.net package.

Syntax

protected void set(String protocol, String host, int port, String file, String ref)

Parameters

protocol

The protocol (http, news, etc) to use for this URL.

host

The Internet name of the host machine to connect to (e.g., www.syr.edu).

port

The port number on the host machine to connect to.

file

The path name of the file on the host.

ref

The name of the reference that indicates a specific offset into the file.

Description

This method is provided so that the parseURL method of the URLStreamHandler class can set the fields of a URL. It is a protected method that is accessible only to classes in the java.net package.

Imports

import java.net.URL;

Returns

None.

Example

This method can only be invoked by classes in the java.net package and hence no example code illustrating the usage of this method is provided here.

setURLStreamHandlerFactory(URLStreamHandlerFactory)

ClassName

URL

Purpose

Specifies the factory object (that implements the URLStreamHandlerFactory interface) that all URL objects should use to create protocol-specific URLStreamHandler objects.

Syntax

public static synchronized void setURLStreamHandlerFactory(URLStreamHandlerFactory fac)

Parameters

fac

The URLStreamHandlerFactory object that must be used for creating protocol-specific stream handlers.

Description

All objects of the URL class share the same URLStreamHandlerFactory object. By invoking this method, you can install your own URLStreamHandlerFactory. An error is generated if a URLStreamHandlerFactory already exists. If you write new protocol handler classes and install these classes in nonstandard locations, you will need to create a class that implements the URLStreamHandlerFactory interface. This factory class will need to know where to find the protocol-specific implementations of classes such as the URLConnection class and the URLStreamHandler class.

Imports

import java.net.URL;

See Also

The URLStreamHandlerFactory class and the URLStreamHandler class described in this chapter

Returns

None.

Example

The following pieces of code illustrate how you might set the URLStreamHandlerFactory to a custom factory that you have implemented.

// File: myFactory.java
import java.net.*;

public class myFactory implements URLStreamHandlerFactory
..


// File: URLSetFactoryTest.java
import java.net.*;

public class URLSetFactoryTest catch (MalformedURLException e)
}

toExternalForm()

ClassName

URL

Purpose

Represents this URL as a text string.

Syntax

public String toExternalForm()

Parameters

None.

Description

The textual representation of this URL is constructed from the individual fields of the URL (such as protocol, hostname, etc.). Default values (such as default port number) are omitted from the text string.

Imports

import java.net.URL;

Returns

The String object returned by this method contains a text string that specifies the protocol, hostname, portnumber (if specified), file name, and reference (if specified) of this URL object.

See Also

The toString method of this class

Example

This method is invoked by the toString method of this class. The following Java class shows how to invoke this method in your application.

import java.net.*;

public class URLTestExternalForm catch (MalformedURLException e)
}

When this example is compiled (javac URLTestExternalForm.java) and executed (java URLTestExternalForm), the following string is printed on the screen.

u1.toExternalForm = https://web.syr.edu:80/index.html

toString()

ClassName

URL

Purpose

Represents this URL as a text string.

Syntax

public String toString()

Parameters

None.

Description

This method simply invokes the toExternalForm method to represent the URL object as a text string.

Imports

java.net.URL;

Returns

The String object returned by this method contains a text string that specifies the protocol, hostname, port number (if specified), file name, and reference (if specified) of this URL object.

See Also

The toExternalForm method of this class

Example

The use of this method is illustrated in the showParams method in the URLPanel class of the section project (Step 5) at the end of this chapter.

URLConnection

Purpose

Sets/modifies the connection-session parameters and handles the network connection to the remote object referred to by a Uniform Resource Locator.

Syntax

public class URLConnection extends Object

Description

This abstract class must be subclassed by protocol-implementors to provide protocol-specific implementations for connecting to remote objects referred to by Uniform Resource Locators (URLs). This class will handle the parsing of protocol-specific message headers and message content. The various properties of the connection session for a protocol will also be handled by subclasses of this class. All instances of the URLConnection class share a table of ContentHandlers. These ContentHandlers represent specific MIME-type/subtype combinations. Instances of this class (for a specific protocol) are created by the subclass of the URLStreamHandler class that implements the specified protocol's stream handling functionality. Figure 11-2 shows the basic relationships between URLs, ProtocolHandlers, and ContentHandlers. Figure 11-6 shows the inheritance diagram for the URLConnection class.


Figure 11-6  Inheritance diagram for the URLConnection class

PackageName

java.net

Imports

import java.net.URLConnection;

Constructors

protected URLConnection(URL url)

Parameters

url

The URL object to which a connection needs to be established.

Example

The constructor method for this class is protected and hence you cannot create objects of this class. To implement protocol handlers, you will need to extend this class.

connect()

ClassName

URLConnection

Purpose

Connects to the remote object referred to by the URL for which this URLConnection object was created.

Syntax

public abstract void connect() throws IOException

Parameters

None.

Description

Invoking this method causes a connection to be established to the object referred to by the URL. The properties of this connection-session cannot be altered (using the methods such as setDoInput and setDoOutput) once a connection is established. This method must be implemented by any class that extends the URLConnection class.

Imports

import java.net.URLConnection;

Returns

None.

Example

The following code shows a portion of a Java class that extends the URLConnection class.

// File: CustomURLConnection.java
URLConnection object for a new protocol
package CustomProtocolConnection;
import java.net.*;

public class CustomURLConnection extends URLConnection


getAllowUserInteraction()

ClassName

URLConnection

Purpose

Returns the value of the flag that indicates whether the protocol permits user interaction while establishing the connection to the remote object.

Syntax

public boolean getAllowUserInteraction()

Parameters

None.

Description

Protocols such as http, that have access/security control features, allow user interaction (such as authentication by asking for a user name and password) during the process of setting up a connection to an object referred to in a URL. Protocol implementors specify whether this interaction is permitted by the protocol or not.

Imports

import java.net.URLConnection;

Returns

The return value is true if the protocol permits user-interaction at the time of establishing a connection, and false if user-interaction is not permitted by the protocol.

See Also

The setAllowUserInteraction, getDefaultAllowUserInteraction and setDefaultAllowUserInteraction methods of this class

Example

The following example illustrates the usage of this method and some of the other related methods of this class.

// File: URLConnTest1.java
Illustrates the usage of some of the methods of the
URLConnection class

import java.net.*;
import java.io.IOException;

public class URLConnTest1 catch (IOException ie)
} catch (MalformedURLException e)
}

When this program is compiled and executed it prints the following messages on the screen.

URL: https://cosmos/∼asriniva/index.html
getAllowUserInteraction: false
getDefaultAllowUserInteraction: false
getUseCaches: true
getDefaultUseCaches: true
getDoInput: true
getDoOutput: false

getContent()

ClassName

URLConnection

Purpose

Reads the data from the remote object and constructs an instance of the subclass of ContentHandler that handles the MIME-type of the object this URL refers to.

Syntax

public Object getContent() throws IOException

Parameters

None.

Description

This method determines the MIME-type/subtype of the object referred to by the URL and constructs the appropriate ContentHandler (if it does not already exist). The getContent method of the ContentHandler class is invoked and the ContentHandler object reads the data from this URLConnection stream. Then it constructs and returns the object referred to by the URL. For example, a plain text content handler may just read the data from the URLConnection object and return a String object containing the text read from the remote object, or a content handler that handles the image/gif MIME-type could construct a GIFImage object. This GIFImage object would typically be an instance of a subclass of the Image class.

Imports

import java.net.URLConnection;

Returns

The Object returned by this method is constructed from the data read from the URLConnection. Depending on the MIME-type of the object referred to by the URL, a specific instance of a class that represents that content is created. The instanceof operator should be used to determine the class that this object belongs to. An IOException indicates that an error occurred while reading and interpreting data from the remote object.

See Also

The ContentHandler class and the getContent method of the URL class and of the URLStreamHandler class. These are described in this chapter.

Example

The following example uses the getContent method of the URLConnection class to access the object referred to by the URL.

// File: URLConnContentType.java
import java.net.*;
import java.io.IOException;

public class URLConnContentType
} catch (IOException ie)
} catch (MalformedURLException e)
}

This program prints the following on the screen.

This URL refers to a String object

Contents of the URL object: This is the only line of text in hello.txt!

getContentEncoding()

ClassName

URLConnection

Purpose

Gets the mechanism used to encode the data of the remote object to which this URLConnection is connected.

Syntax

public String getContentEncoding()

Parameters

None.

Description

One of the MIME header fields that specifies information about the object is the Content-Encoding field. It specifies the encoding mechanism used to encode the object data. Content codings are primarily used to allow data to be compressed or encrypted. Encoding mechanisms such as compress and gzip are used to compact the data so that less data needs to be transferred over the network.

Imports

import java.net.URLConnection;

Returns

This method returns a String that specifies the encoding mechanism used. If the encoding mechanism is not known, this method returns a null value. Two common encoding mechanisms are x-compress and x-gzip.

Example

The following example illustrates the usage of some of the methods of this class.

// File: URLConnTest.java
Illustrates the usage of some of the methods of the
URLConnection class
import java.net.*;
import java.io.IOException;
import java.util.Date;

public class URLConnTest catch (IOException ie)
} catch (MalformedURLException e)
}

When this program is compiled (javac URLConnTest.java) and run (java URLConnTest), the following text is printed on the screen.

URL: https://cosmos/∼asriniva/index.html
Content-Type: text/html
Content-Length: 443
Content-Encoding: null
Date (value): 829693487000 (string): Tue Apr 16 18:24:47 EDT 1996
Last modified on (value): 829686465000 (string): Tue Apr 16 16:27:45
EDT 1996
Expires on: 0

getContentLength()

ClassName

URLConnection

Purpose

Gets the length of the content of the remote object that this URLConnection is connected to.

Syntax

public int getContentLength()

Parameters

None.

Description

One of the MIME header fields that specifies information about the object is the Content-Length field. It implies that the object data should be treated as binary data, and the integer value associated with this field specifies the data size of the remote object.

Imports

import java.net.URLConnection;

Returns

The integer value returned by this method specifies the size of the content of the remote object. If the content length cannot be determined, this method returns the value -1.

Example

This method is used in the example for the getContentEncoding method of this class.

getContentType()

ClassName

URLConnection

Purpose

Gets the MIME-type/subtype combination of the remote object that this URLConnection is connected to.

Syntax

public String getContentType()

Parameters

None.

Description

The value associated with the Content-Type field of the MIME header specifies the MIME-type and subtype of the object that the URL refers to.

Imports

import java.net.URLConnection;

Returns

The String returned by this method contains the MIME-type and subtype combination of the remote object. If the content type is not known, this method returns a null value. For example, if the URL referred to a HTML file, this method would return text/html, whereas if the URL referred to a postscript file, the string returned by this method would be application/postscript.

Example

This method is used in the example for the getContentEncoding method of this class.

getDate()

ClassName

URLConnection

Purpose

Gets the date and time that the object was sent.

Syntax

public long getDate()

Parameters

None.

Description

One of the MIME header fields is the Date field. The value associated with this field specifies the date and time that the data, accompanying this header, was sent. The Date field of the MIME header contains a string representation of the date, such as the following text.

Mon, 15 Apr 1996 09:00:00 GMT

This method invokes the parse method of the Date class to convert this string representation into a time value, and returns this time value.

Imports

import java.net.URLConnection;

Returns

The value returned by this method is obtained by invoking the parse method of the Date class which returns the number of milliseconds since the beginning epoch, for the specified date. If the date is not known, the value 0 is returned.

See Also

The parse method of the Date class. This class is described in Chapter 13.

Example

This method is used in the example for the getContentEncoding method of this class. The Date class is used to convert the number returned by this method to a string representation of a date and time.

getDefaultAllowUserInteraction()

ClassName

URLConnection

Purpose

Gets the default value of the flag that indicates whether the protocol permits user-interaction while establishing the connection to the remote object.

Syntax

public static boolean getDefaultAllowUserInteraction()

Parameters

None.

Description

This method can be used to determine whether or not the protocol permits user-interaction. This property is required of some protocols that require user-interaction, such as typing in a password, before proceeding further. The variable that stores the value of the flag associated with this property is a static variable in the URLConnection class. This ensures uniformity in this policy among all instances of the URLConnection class for that protocol.

Imports

java.net.URLConnection;

Returns

The return value is true or false, depending on whether or not the default value associated with this property for this protocol is true or false. The default value for this variable is false.

See Also

The setDefaultAllowUserInteraction method; the getAllowUserInteraction and the setAllowUserInteraction methods of this class

Example

This method is used in the example for the getAllowUserInteraction method of this class.

getDefaultRequestProperty(String)

ClassName

URLConnection

Purpose

Gets the default value associated with the specified field of the request header.

Syntax

public static String getDefaultRequestProperty(String key)

Parameters

key

The name of the request header field for which the default value is to be returned.

Description

In a protocol transaction such as http, the client sends a list of fields to the http server. Some of these fields (such as Accept and Accept Encoding) convey information about the capabilities of the client. This method is used to determine the default values associated with a specified field of the request header. The request fields (properties) contained in a HTTP protocol header are

From

Accept

Accept-Encoding

Accept-Language

User-Agent

Referrer

Authorization

Charge-to

If-Modified-Since

Pragma

Imports

import java.net.URLConnection;

Returns

This method returns a String object that contains a default value associated with the specified property. The default implementation of this method (in the URLConnection class) simply returns a null string.

See Also

The setDefaultRequestProperty method of this class

Example

The following example shows how you can override this method.

// File: CustomURLConnection.java
URLConnection object for a new protocol
package CustomProtocolConnection;
import java.net.*;

public class CustomURLConnection extends URLConnection


To access the contents, click the chapter and section titles.

Java Networking & AWT API SuperBible
(Publisher: Macmillan Computer Publishing)
Author(s): NAGARATNAM, MASO, & SRINVASAN
ISBN: 157169031x
Publication Date: 07/12/96

Search this book:
 

Previous

Table of Contents

Next

getDefaultUseCaches()

ClassName

URLConnection

Purpose

Gets the default value of the flag that indicates whether the protocol should use the cache to retrieve an object or whether it should ignore the cache and fetch the object from the remote site.

Syntax

public boolean getDefaultUseCaches()

Parameters

None.

Description

Some protocols use local caches to enable quick access to previously retrieved objects. The URLConnection class maintains a per-instance boolean variable that indicates whether or not to use caching. A static boolean variable specifies the default value for the per-instance variable. This method returns the value of the static boolean variable.

Imports

import java.net.URLConnection;

Returns

The return value is true or false, depending on whether the URLConnection should use the cache or ignore the cache. The default value for this variable is true.

See Also

The setDefaultUseCaches method the setUseCaches and getUseCaches methods of this class

Example

This method is used in the example for the getAllowUserInteraction method of this class.

getDoInput()

ClassName

URLConnection

Purpose

Gets the value of the flag that indicates whether this URLConnection can be used for input (i.e. can be read from).

Syntax

public boolean getDoInput()

Parameters

None.

Description

The value returned by this method indicates whether or not data can be read from the URLConnection.

Imports

import java.net.URLConnection;

Returns

The boolean value returned is true if the URLConnection can be used for input and false if not. The default value for this flag is true.

See Also

The setDoInput method of this class

Example

This method is used in the example for the getAllowUserInteraction method of this class.

getDoOutput()

ClassName

URLConnection

Purpose

Gets the value of the flag that indicates whether this URLConnection can be used for output (i.e., can be written to).

Syntax

public boolean getDoOutput()

Parameters

None.

Description

The value returned by this method indicates whether or not data can be written to the remote object that the URLConnection is connected to.

Imports

import java.net.URLConnection;

Returns

The boolean value returned is true if the URLConnection can be used for output and false if not. The default value for this flag is false.

See Also

The setDoOutput method of this class

Example

This method is used in the example for the getAllowUserInteraction method of this class.

getExpiration()

ClassName

URLConnection

Purpose

Gets the date after which the information retrieved from the remote object ceases to be valid and must be reloaded.

Syntax

public long getExpiration()

Parameters

None.

Description

One of the MIME header fields that specifies information about the object is the Expires field. The value associated with this field specifies the date after which the information already retrieved ceases to be valid and must be retrieved again. The object referred to by the URL is considered to be stale after the date/time specified in this field. This allows the data to be refreshed periodically and also allows a limited amount of control over caching policies. The Expires field of the MIME header contains a string representation of the date, such as the following text.

Mon, 15 Apr 1996 09:00:00 GMT

This method invokes the parse method of the Date class to convert this string representation into a time value, and returns this time value.

Imports

import java.net.URLConnection;

Returns

The return value indicates the date after which the object needs to be retrieved again. The value returned by this method is obtained by invoking the parse method of the Date class that returns the number of milliseconds since the beginning epoch, for the specified date. If the expiration date is not known then the value 0 is returned.

See Also

The parse method of the Date class. This class is described in Chapter 13.

Example

This usage of this method is illustrated in the example for the getContentEncoding method of this class.

getHeaderField(int)

ClassName

URLConnection

Purpose

Gets the value associated with the nth header field of the object's header.

Syntax

public String getHeaderField(int n)

Parameters

n

The index number of the header field whose value is to be retrieved.

Description

This method retrieves the value associated with a particular header field. The header field is specified using an index. Without knowing the actual field names contained in the header, one can use this method and the GetHeaderFieldKey method to iterate through all the header field names and associated values. The index n starts at zero.

Imports

import java.net.URLConnection;

Returns

If the index n is less than the number of fields in the header, then the value for that field is returned. If n is greater than the number of fields in the header, the return value is null. The default implementation of this method (in the URLConnection class) simply returns a null string.

See Also

The URLConnection.getHeaderField(String) method

Example

Please refer to the example for the getDefaultRequestProperty method of this class to see how you can provide a custom implementation of this method in any class that extends the URLConnection class.

getHeaderField(String)

ClassName

URLConnection

Purpose

Gets the value associated with the specified header field.

Syntax

public String getHeaderField(String name)

Parameters

name

The name of the header field whose value is to be retrieved.

Description

This method retrieves the value associated with a specified header field. The header field is specified by name (e.g,. Content-Type).

Imports

import java.net.URLConnection;

Returns

The String object returned by this method contains the value associated with the specified field name. If the header field name was not found in the data stream read from the remote object, then the value returned by this method is null. The default implementation of this method (in the URLConnection class) simply returns a null string. The header fields given with or in relation to objects in HTTP are

Allowed

Public

Content-Length

Content-Type

Content-Transfer-Encoding

Content-Encoding

Date

Expires

Last-Modified

Message-Id

URL

Version

Derived-From

Content-Language

Cost

Link

Title

See Also

The getHeaderField method of this class

Example

Please refer to the example for the getDefaultRequestProperty method of this class to see how you can provide a custom implementation of this method in any class that extends the URLConnection class.

getHeaderFieldDate(String, long)

ClassName

URLConnection

Purpose

Gets the value associated with the specified header field, reads this value as a date value, and returns the date value.

Syntax

public long getHeaderFieldDate(String name, long strDef)

Parameters

name

The name of the header field whose value is to be retrieved as a date value.

strDef

The default value to return if the header field name is not found.

Description

This method reads the value associated with the header field and returns this value as a date value. This method can be used by protocols that have pre-parsed headers where the formats of individual fields are known. Please refer to the getDate method description for the format of the date value returned by this method.

Imports

import java.net.URLConnection;

Returns

This method returns the value specified in strDef if the field name is not known. If the field name is found, the value associated with it is returned as a long integer.

Example

This helper method, shown below, can be used to extract the contents of a field and convert it into a long integer representing the number of milliseconds since the epoch.

// File: CustomURLConnection.java
URLConnection object for a new protocol
package CustomProtocolConnection;
import java.net.*;

public class CustomURLConnection extends URLConnection


getHeaderFieldInt(String, int)

ClassName

URLConnection

Purpose

Gets the value associated with the specified header field, reads this value as an integer value, and returns the integer value.

Syntax

public int getHeaderFieldInt(String name, int valDef)

Parameters

name

The name of the header field whose value is to be retrieved as an integer value.

valDef

The default value to return if the header field name is not found.

Description

This method reads the value associated with the header field and returns this value as an integer value. This method can be used by protocols that have pre-parsed headers, where the formats of individual fields are known.

Imports

java.net.URLConnection;

Returns

This method returns the value specified in valDef if the field name is not known. If the field name is found, the value associated with it is returned as an integer.

Example

This helper method can be used in a manner similar to that described in the example for the getHeaderFieldDate method description.

getHeaderFieldKey(int)

ClassName

URLConnection

Purpose

Gets the field name of the nth header field.

Syntax

public String getHeaderFieldKey(int n)

Parameters

n

The index number of the header field whose field name is to be retrieved.

Description

This method retrieves the field name associated with a particular header field. The header field is specified using an index. Without knowing the actual field names contained in the header, one can use this method and the GetHeaderField (int) method to iterate through all the header field names and their associated values. The index n starts at zero.

Imports

import java.net.URLConnection;

Returns

If index n is less than the number of fields in the header, then the field name for that field is returned. If n is greater than the number of fields in the header, the return value is null. The default implementation of this method (in the URLConnection class) simply returns a null string.

See Also

The getHeader method of this class

Example

Please refer to the example for the getDefaultRequestProperty method of this class to see how you can provide a custom implementation of this method in any class that extends the URLConnection class.

getIfModifiedSince()

ClassName

URLConnection

Purpose

Gets the time that is sent as the value of the If-Modified-Since header field of the request header to determine whether or not an object should be retrieved.

Syntax

public long getIfModifiedSince()

Parameters

None.

Description

The If-Modified-Since field of the request header is sent by the client to the server in order to make the retrieval of an object conditional. By specifying a time with this header field, the client instructs the server not to send the object, if the object has not changed since the time indicated, as the value for this header field. This method gets the value associated with this field.

Imports

import java.net.URLConnection;

Returns

The return value is a long integer that indicates the time that should be used by a server to determine whether an object has been modified or not.

Example

This method can be used in a manner similar to the getLastModified method.

getInputStream()

ClassName

URLConnection

Purpose

Gets an input stream from which data from the remote object can be read.

Syntax

public InputStream getInputStream() throws IOException

Parameters

None.

Description

This method opens and returns an InputStream to the remote object that this URLConnection object is connected to. The object's data can be read using the InputStream object returned by this method. Protocols that permit input must implement this method.

Imports

import java.net.URLConnection;

Returns

This method returns an InputStream object that can be used to read data from the remote object. An UnknownServiceException is generated if the protocol does not support input. The default implementation of this method (in the URLConnection class) simply throws an UnknownServiceException.

Example

This method is used in the example for the openConnection method of the URL class.

getLastModified()

ClassName

URLConnection

Purpose

Gets the time that the object that this URLConnection is connected to was last modified.

Syntax

public long getLastModified()

Parameters

None.

Description

One of the MIME header fields that specifies information about the object is the Last-Modified field. The value associated with this field specifies the time that the object was last modified. The format of this field is the same as the date format for the Date field described in the getDate method of this class. The server compares this value against the value of the If-Modified-Since field of the request header to determine whether the object needs to be sent to the client.

Imports

import java.net.URLConnection;

Returns

The return value indicates the time that the object this URLConnection is connected to was last modified. If the time is not known, the value 0 is returned.

See Also

The getIfModifiedSince method of this class; the parse method of the Date class, and the Date class, described in Chapter 13.

Example

An example of this method is illustrated in the example for the getContentEncoding method of this class.

getOutputStream()

ClassName

URLConnection

Purpose

Gets an output stream that the remote object can be written to.

Syntax

public OutputStream getOutputStream() throws IOException

Parameters

None.

Description

This method opens and returns an OutputStream to the remote object that this URLConnection object is connected to. Data can be written to the object using the OutputStream object returned by this method. Writing to a URLConnection is similar to the POST method of the HTTP protocol. It provides a means by which information can be sent to the object referenced by the URL. You can use the output stream of a URLConnection to send data back to CGI (Common Gateway Interface) scripts that are running on a World Wide Web server. Protocols that permit output must implement this method.

Imports

import java.net.URLConnection;

Returns

This method returns an OutputStream object. An UnknownServiceException is generated if the protocol does not support output. The default implementation of this method (in the URLConnection class) simply throws an UnknownServiceException.

Example

The following example is a simple template that you can use to write Java programs that post and receive data to or from CGI scripts.

// File: URLConnWrite.java
A template for interacting with CGI scripts

import java.net.*;
import java.io.*;

public class URLConnWrite
di.close(); // close
the input stream
} catch (IOException ie)
} catch (MalformedURLException e)
}

The output of this program is:

Line 1: <HTML>
Line 2: <HEAD>
Line 3: <TITLE>CGI/1.0 TCL script report:</TITLE>
Line 4: </HEAD>
Line 5: <BODY>
Line 6: <H1>Command Line Arguments</H1>
Line 7: argc is 0. argv is .
Line 8:
Line 9: <H1>Message</H1>
Line 10: <PRE>
Line 11: query = Java AND book AND Waite
Line 12:
Line 13: </PRE>
Line 14: <H1>Environment Variables</H1>
Line 15: <DL>
Line 16: <DT>SERVER_SOFTWARE<DD>NCSA/1.3
Line 17: <DT>SERVER_NAME<DD>199.100.97.2
Line 18: <DT>GATEWAY_INTERFACE<DD>CGI/1.1
Line 19: <DT>SERVER_PROTOCOL<DD>HTTP/1.0
Line 20: <DT>SERVER_PORT<DD>80
Line 21: <DT>REQUEST_METHOD<DD>POST
Line 22: <DT>SCRIPT_NAME<DD>/cgi-bin/test-cgi.tcl
Line 23: <DT>QUERY_STRING<DD>
Line 24: <DT>REMOTE_HOST<DD>cosmos
Line 25: <DT>REMOTE_ADDR<DD>199.100.97.2
Line 26: <DT>CONTENT_TYPE<DD>application/x-www-form-urlencoded
Line 27: <DT>CONTENT_LENGTH<DD>30
Line 28: <DT>HTTP_ACCEPT<DD>
Line 29: */*;
Line 30: *;
Line 31: image/gif,
Line 32: image/jpeg,
Line 33: q=.2
Line 34: q=.2,
Line 35: text/html,
Line 36: </DL>
Line 37: </BODY>
Line 38: </HTML>

getRequestProperty()

ClassName

URLConnection

Purpose

Gets the value associated with the specified request header field name.

Syntax

public String getRequestProperty(String key)

Parameters

key

The request header field name whose associated value is to be returned

Description

In a protocol transaction such as http, the client sends a list of fields to the http server. These fields are part of the request header. In the http protocol, From, Accept, If-Modified-Since, and Pragma are some of the field names sent in the request header. A more comprehensive list of property names is listed in the getDefaultRequestProperty method description. This method is used to retrieve the value associated with a specific property. This method should not be invoked if the URLConnection object is already "connect()"ed.

Imports

import java.net.URLConnection;

Returns

The String returned by this method contains the value of the request header field. If the header field is not found, then the null value is returned. The default implementation of this method (in the URLConnection class) throws an IllegalAccessError if the URLConnection object is already connected; otherwise it returns a null string.

See Also

The setRequestProperty method of this class

Example

Please refer to the example for the getDefaultRequestProperty method of this class to see how you can provide a custom implementation of this method in any class that extends the URLConnection class.

getURL()

ClassName

URLConnection

Purpose

Gets the URL object to which this connection was established.

Syntax

public URL getURL()

Parameters

None.

Description

This method simply returns the URL object that was supplied as a parameter to the URLConnection constructor.

Imports

import java.net.URLConnection;

Returns

This method returns the URL object that this URLConnection established a connection to.

Example

This usage of this method is illustrated in the following example.

// File: URLConnTest.java
Extracts and prints the URL string specification associated with
an URLConnection object
import java.net.*;
import java.io.IOException;

public class URLConnTest catch (IOException ie)
} catch (MalformedURLException e)
}

getUseCaches()

ClassName

URLConnection

Purpose

Gets the value of the flag that indicates whether this URLConnection object should use the cache to retrieve an object or whether it should ignore the cache and fetch the object from the remote site.

Syntax

public boolean getUseCaches()

Parameters

None.

Description

Some protocols use local caches to enable quick access to previously retrieved objects. The URLConnection class maintains a per-instance boolean variable that indicates whether or not to use caching. This method returns the value of this boolean variable.

Imports

import java.net.URLConnection;

Returns

The return value is true or false, depending on whether the URLConnection should use the cache or ignore the cache. The default value returned by this method is true.

See Also

The setUseCaches method; the setDefaultUseCaches method and getDefaultUseCaches methods of this class

Example

This method is used in the example for the getAllowUserInteraction method of this class.

guessContentTypeFromName(String)

ClassName

URLConnection

Purpose

Guesses the MIME-type/subtype of the specified object by examining its name.

Syntax

static protected String guessContentTypeFromName(String fname)

Parameters

fname

The specification of the remote object (can be a text representation of a URL or just a plain file name).

Description

This method tries to determine the MIME-type of the specified object,by examining the file name extension of the object. The file name extension is compared against a list of extensions for which the MIME-type/subtype combinations are known. For example, if fname was https://www.syr.edu/smiley.gif, then the .gif extension would have been identified as a known MIME-type and would have returned the string image/gif. The following is a list of file name extensions and the corresponding MIME-type/subtype combinations that this method returns.

Extension MIME-type/subtype
<None> content/unknown
.uu application/octet-stream
.saveme application/octet-stream
.dump application/octet-stream
.hqx application/octet-stream
arc application/octet-stream
.o application/octet-stream
.a application/octet-stream
.bin application/octet-stream
.exe application/octet-stream
.z application/octet-stream
.gz application/octet-stream
.oda application/oda
.pdf application/pdf
.eps application/postscript
.ai application/postscript
.ps application/postscript
.rtf application/rtf
.dvi application/x-dvi
.hdf application/x-hdf
.latex application/x-latex
.cdf application/x-netcdf
.nc application/x-netcdf
.tex application/x-tex
.texinfo application/x-texinfo
.texi application/x-texinfo
.t application/x-troff
.tr application/x-troff
.roff application/x-troff
.man application/x-troff-man
.me application/x-troff-me
.ms application/x-troff-ms
.src application/x-wais-source
.wsrc application/x-wais-source
.zip application/zip
.bcpio application/x-bcpio
.cpio application/x-cpio
.gtar application/x-gtar
.shar application/x-shar
.sh application/x-shar
.sv4cpio application/x-sv4cpio
.sv4crc application/x-sv4crc
.tar application/x-tar
.ustar application/x-ustar
.snd audio/basic
.au audio/basic
.aifc audio/x-aiff
.aif audio/x-aiff
.aiff audio/x-aiff
.wav audio/x-wav
.gif image/gif
.ief image/ief
.jfif image/jpeg
.jfif-tbnl image/jpeg
.jpe image/jpeg
.jpg image/jpeg
.jpeg image/jpeg
.tif image/tiff
.tiff image/tiff
.ras image/x-cmu-rast
.pnm image/x-portable-anymap
X.pbm image/x-portable-bitmap
.pgm image/x-portable-graymap
.ppm image/x-portable-pixmap
.rgb image/x-rgb
.xbm image/x-xbitmap
.xpm image/x-xpixmap
.xwd image/x-xwindowdump
.htm text/html
.html text/html
.text text/plain
.c text/plain
.cc text/plain
.c++ text/plain
.h text/plain
.pl text/plain
.txt text/plain
.java text/plain
.rtx application/rtf
.tsv text/tab-separated-values
.etx text/x-setext
.mpg video/mpeg
.mpe video/mpeg
.mpeg video/mpeg
.mov video/quicktime
.qt video/quicktime
.avi application/x-troff-msvideo
.movie video/x-sgi-movie
.mv video/x-sgi-movie
.mime message/rfc822

Imports

import java.net.URLConnection;

Returns

If the extension of the specified object matched a known extension, then the corresponding MIME-type/subtype combination is returned. The string content/unknown is returned for file names whose extensions do not match any of the known extensions.

See Also

The guessContentTypeFromStream method of this class

Example

This protected method can only be accessed by subclasses of the URLConnection class and by classes in the java.net package. The following code sample shows how you might invoke this method within a class that extends the URLConnection class.

// File: CustomURLConnection.java
URLConnection object for a new protocol
package CustomProtocolConnection;
import java.net.*;

public class CustomURLConnection extends URLConnection


guessContentTypeFromStream(InputStream)

ClassName

URLConnection

Purpose

Guesses the MIME-type/subtype of the specified object by inspecting the data read from the specified InputStream.

Syntax

static protected String guessContentTypeFromStream(InputStream is) throws IOException

Parameters

is

The InputStream that is connected to the remote object whose content type is to be determined

Description

This method tries to determine the content type of an object by reading and examining data from the object. Many content types such as image files have magic strings as part of the header of the object that identify the object as a particular image format. Use this method with care!

Imports

import java.net.URLConnection;

Returns

If a valid content type is detected, this method returns the MIME-type/subtype combination of the object; otherwise, it returns a null value.

See Also

The guessContentTypeFromName method of this class

Example

This protected method can only be accessed by subclasses of the URLConnection class and by classes in the java.net package. This method can be used in a manner similar to the way that the guessContentTypeFromName is used. The difference between the two is that the parameter supplied to this method is an InputStream object instead of a file name.

setAllowUserInteraction(boolean)

ClassName

URLConnection

Purpose

Sets the value of the flag that indicates whether the protocol permits user-interaction while establishing the connection to the remote object.

Syntax

public void setAllowUserInteraction(boolean bFlag)

Parameters

bFlag

The boolean value that, if set to true, allows user-interaction or, if set to false, disables user-interaction.

Description

Protocols such as http, that have access and security control features, allow user-interaction (such as authentication by asking for a user name and password) during the process of setting up a connection to an object referred to in a URL. Protocol implementors must specify whether this interaction is permitted by the protocol or not. This variable is maintained on a per-instance basis for the URLConnection class. This method cannot be invoked if the URLConnection object is already "connect()"ed.

Imports

import java.net.URLConnection;

Returns

None.

See Also

The getAllowUserInteraction, getDefaultAllowUserInteraction, and the setDefaultAllowUserInteraction methods of this class

Example

The following example illustrates how you might invoke this method to manipulate whether or not to allow user-interaction.

import java.net.*;
import java.io.IOException;

public class URLConnTest1 catch (IOException ie)
} catch (MalformedURLException e)
}

setContentHandlerFactory(ContentHandlerFactory)

ClassName

URLConnection

Purpose

Specifies the factory object (that implements the ContentHandlerFactory interface) that knows how to create content-specific ContentHandler objects.

Syntax

public static synchronized void setContentHandlerFactory(ContentHandlerFactory factory)

Parameters

factory

The ContentHandlerFactory object that must be used to create content-specific content handlers.

Description

All objects of the URLConnection class share the same ContentHandlerFactory object. By invoking this method, you can install your own ContentHandlerFactory. An error is generated if a ContentHandlerFactory already exists. If you write new content handler classes and install these classes in nonstandard locations, then you will need to create a class that implements the ContentHandlerFactory interface. This class will need to know where to find the content-specific implementations of the ContentHandler class.

Imports

java.net.URLConnection;

Returns

None.

See Also

The ContentHandlerFactory class described in this chapter

Example

The following code sample shows how you can direct the URLConnection class to use a custom ContentHandlerFactory object.

import java.net.*;
import CustomPackage.CustomContentHandlerFactory;

..
..
// in the context of a method in your Java application
CustomContentHandlerFactory f = new CustomContentHandler
Factory();
URLConnection.setContentHandlerFactory(f);
// henceforth, all URLConnections will use this new factory
object to
// create content handlers
..
..

setDefaultAllowUserInteraction(boolean)

ClassName

URLConnection

Purpose

Sets the default value of the flag that indicates whether the protocol permits user-interaction while establishing the connection to the remote object.

Syntax

public static void setDefaultAllowUserInteraction(boolean bFlag)

Parameters

bFlag

The default boolean value for this property.

Description

The variable that stores the value of the flag associated with this property is a static variable in the URLConnection class. Setting this variable will affect all future connections made by URLConnection classes created henceforth.

Imports

import java.net.URLConnection;

Returns

None.

See Also

The getDefaultAllowUserInteraction, getAllowUserInteraction, and setAllowUserInteraction methods of this class

Example

This method is a static method of the URLConnection class and does not need an object reference to invoke the method. You can invoke the method by prefixing it with the class name as shown here:

. // somewhere in your Java application
URLConnection.setDefaultAllowUserInteraction(true);
..

setDefaultRequestProperty(String, String)

ClassName

URLConnection

Purpose

Sets the default value associated with the specified field of the request header.

Syntax

public static void setDefaultRequestProperty(String fieldName, String fieldValue)

Parameters

fieldName

The name of the field in the request header.

fieldValue

The default value to assign to the above field.

Description

In a protocol transaction such as http, the client sends a list of fields to the http server. Some of these fields (such as Accept and Accept Encoding) convey information about the capabilities of the client. This method is used to set the default values associated with a specified field of the request header. For example, you may set the default value of the Accept field to text/plain, text/html, and image/gif. Doing this allows the client to inform the server that it can accept plain files and HTML files, as well as GIF images. The values set here are used for initialization whenever a URLConnection object is constructed. The default implementation of this method (in the URLConnection class) does nothing.

Imports

import java.net.URLConnection;

Returns

None.

See Also

The getDefaultRequestProperty method of this class

setDefaultUseCaches(boolean)

ClassName

URLConnection

Purpose

Sets the default value of the flag that indicates whether the protocol should use the cache to retrieve an object or whether it should ignore the cache and fetch the object from the remote site.

Syntax

public void setDefaultUseCaches(boolean bFlag)

Parameters

bFlag

The default boolean value for this property.

Description

Some protocols use local caches to enable quick access to previously retrieved objects. The URLConnection class maintains a per-instance boolean variable that indicates whether to use caching or not. A static boolean variable specifies the default value for the per-instance variable. This method sets the value of the static boolean variable. Setting this value affects all URLConnection objects created hereafter.

Imports

import java.net.URLConnection;

Returns

None.

See Also

The getDefaultUseCaches, setUseCaches, and getUseCaches methods of this class

setDoInput(boolean)

ClassName

URLConnection

Purpose

Sets the value of the flag that indicates whether this URLConnection can be used for input (i.e., can be read from).

Syntax

public void setDoInput(boolean bFlag)

Parameters

bFlag

The boolean value for this property. If set to true, this URLConnection object can be read from.

Description

The parameter bFlag specifies whether or not this URLConnection object can be used for input. If it is set to false, data cannot be read from this URLConnection object. This method should not be invoked if the URLConnection object is already "connect()"ed.

Imports

import java.net.URLConnection;

Returns

None.

See Also

The getDoInput method of this class

setDoOutput(boolean)

ClassName

URLConnection

Purpose

Sets the value of the flag that indicates whether this URLConnection can be used for output (i.e., can be written to).

Syntax

public void setDoOutput(boolean bFlag)

Parameters

bFlag

The boolean value for this property. If set to true, this URLConnection object can be used for output (i.e, it can be written to).

Description

The parameter bFlag specifies whether or not this URLConnection object can be used for output. If it is set to false, data cannot be written to the remote object using this URLConnection object. This method should not be invoked if the URLConnection object is already "connect()"ed.

Imports

import java.net.URLConnection;

Returns

None.

See Also

The getDoOutput method of this class

setIfModifiedSince(long)

ClassName

URLConnection

Purpose

Sets the time sent as the value of the If-Modified-Since header field of the request header to determine whether or not an object should be retrieved.

Syntax

public void setIfModifiedSince(long timeValue)

Parameters

timeValue

The time value that the server should use for comparison to determine whether or not the object is to be sent to this URLConnection.

Description

The If-Modified-Since field of the request header is sent by the client to the server in order to make the retrieval of an object conditional. By specifying a time with this header field, the client instructs the server not to send the object if the object has not changed since the time indicated by the value for this header field. This method sets the value associated with this field. This method should not be invoked if the URLConnection object is already "connect()"ed.

Imports

import java.net.URLConnection;

Returns

None.

setRequestProperty(String, String)

ClassName

URLConnection

Purpose

Sets the value associated with the specified request header field name.

Syntax

public void setRequestProperty(String key, String value)

Parameters

key

The name of the field in the request header.

value

The default value to assign to the above field.

Description

In a protocol transaction such as http, the client sends a list of fields to the http server. These fields are part of the request header. In the http protocol, From, Accept, If-Modified-Since, and Pragma are some of the field names sent in the request header. This method is used to set the value associated with a specific property. This method should not be invoked if the URLConnection object is already "connect()"ed. The default implementation of this method (in the URLConnection class) throws an IllegalAccessError if the URLConnection object is already "connect()"ed.

Imports

import java.net.URLConnection;

Returns

None.

See Also

The getRequestProperty method of this class

setUseCaches(boolean)

ClassName

URLConnection

Purpose

Sets the value of the flag that indicates whether this URLConnection object should use the cache to retrieve an object or whether it should ignore the cache and fetch the object from the remote site.

Syntax

public void setUseCaches(boolean bFlag)

Parameters

bFlag

The boolean value that indicates whether this URLConnection should use the caches or not.

Description

Some protocols use local caches to enable quick access to previously retrieved objects. The URLConnection class maintains a per-instance boolean variable that indicates whether to use caching or not. This method sets the value of this boolean variable. This method should not be invoked if the URLConnection object is already "connect()"ed.

Imports

import java.net.URLConnection;

Returns

None.

See Also

The getUseCaches, setDefaultUseCaches, and getDefaultUseCaches methods of this class

toString()

ClassName

URLConnection

Purpose

Represents the parameters of the URLConnection object as a String.

Syntax

public String toString()

Parameters

None.

Description

This method is used when the parameters associated with this URLConnection object are to be printed as a string. This method is generally used for debugging purposes.

Imports

import java.net.URLConnection;

Returns

This method returns a String object that contains the values of the parameters for this URLConnection object. The default implementation of this method prints the class name and the URL that this URLConnection object was created for. Subclasses of the URLConnection class can override this method to provide more information.

Example

The following example prints the text representation of a URLConnection object.

import java.net.*;
import java.io.IOException;

public class URLConnPrint catch (IOException ie)
} catch (MalformedURLException e)
}

This example prints the following string on the screen:

sun.net.www.protocol.http.HttpURLConnection:https://cosmos/~asriniva/
index.html

URLEncoder

Purpose

Encodes strings into URL format. Encoding a string in this uniform format ensures that the string is not corrupted by errors such as character set variations on different systems.

Syntax

public class URLEncoder extends Object

Description

Some protocols use characters (in the URL specification) that may cause problems due to corruption by imperfect gateways or to a difference in the character sets used in different environments. You will find this class very useful if you are writing Java programs that interact with CGI (Common Gateway Interface) scripts. Figure 11-7 shows the inheritance diagram for the URLEncoder class.


Figure 11-7  Inheritance diagram for the URLEncoder class

PackageName

java.net

Imports

import java.net.URLEncoder;

Constructors

None.

Parameters

None.

Example

Refer to the example for the encode method of this class. This method is also used in the example for the getOutputStream method of the URLConnection class described in this chapter.

encode(String)

ClassName

URLEncoder

Purpose

Returns a URL encoded form of the specified string.

Syntax

public static String encode(String s)

Parameters

s

The string to be encoded.

Description

This method simply translates the text string s into a URL encoded string and returns this string. The following (sets of) characters are left unchanged in the encoded form of the text string: characters A through Z, a through z, 0 through 9 and the underscore character (_). The space character () is replaced with the + sign. All other characters are replaced by a percent sign (%) followed by a 2-digit hexadecimal number. This hexadecimal number represents the value of the character.

Imports

import java.net.URLEncoder;

Returns

This method returns a String object that contains the URL encoded representation of the text in the string s.

Example

Because this method is static, you can invoke it simply by prefixing it with the class name (URLEncoder), as illustrated in the TestEncoder example shown here.

import java.net.URLEncoder;

public class TestEncoder

When this example is compiled (javac TestEncoder.java) and run (java TestEncoder), it produces the following output.

Source string: https://myschool.edu/index.html
URLEncoded version:http%3a%2f%2fmyschool%2eedu%2findex%2ehtml
Source string: A text-string with 6_words
URLEncoded version:A+text%2dstring+with+6_words

URLStreamHandler

Purpose

Specifies an abstract base class that must be subclassed to implement stream handlers for specific protocols (such as http, nntp, ftp, and so on).

Syntax

public class URLStreamHandler extends Object

Description

To implement a protocol handler in Java, you will need to subclass both the URLStreamHandler class and the URLConnection class. The URLStreamHandler object returns a URLConnection object, which is connnected to the specified URL. This URLConnection object implements the specifics of the protocol. This class defines the methods that can be overridden in the subclass to implement the protocol-specific functionality. Except for the constructor, the rest of the methods of this class are protected, which implies that these methods can be accessed only from within the package in which the subclasses are defined. An instance of the subclass that implements the functionality required for a specific protocol is created within the constructor of the URL class. Figure 11-2 shows the basic relationships between URLs, ProtocolHandlers, and ContentHandlers.

By convention, the URLStreamHandler class is always called Handler and it is always created by referring to the absolute path name for the class. The ambiguity of all the URLStreamHandler subclasses being called Handler is resolved by referring to each class using its absolute path name specification. The URL class, by default, looks for a class named Handler in a subdirectory named with the protocol name in the sun/net/www/protocol directory. The sun/net/www/protocol directory structure can be found along with the other standard directories containing the .class files that Java uses. For example, the subclass of the URLStreamHandler class that handles the http protocol will be located in the sun/net/www/protocol/http/Handler.class file. If you are writing protocol handlers, you can either follow this convention or you can write your own class that implements the URLStreamHandlerFactory interface. This factory should know how to create instances of your protocol handlers.

Figure 11-8 shows the inheritance diagram for the URLStreamHandler class.


Figure 11-8  Inheritance diagram for the URLStreamHandler class

PackageName

java.net

Imports

import java.net.URLStreamHandler;

Constructors

public URLStreamHandler()

Parameters

None.

Example

The following code shows how you create a custom URL StreamHandler.

// File: CustomURLConnection.java
URLConnection object for a new protocol
package CustomProtocolConnection;
import java.net.*;

public class CustomURLConnection extends URLConnection

public String getHeaderField(String name)
public InputStream getInputStream() throws IOException


// File: Handler.java
This class will be referred to as sun.net.www.CustomProtocol.
Handler
package sun.net.www.protocol.CustomProtocol;
import java.net.*;
import CustormProtocolConnection.CustomURLConnection;

public class Handler extends URLStreamHandler

openConnection(URL)

ClassName

URLStreamHandler

Purpose

Opens an active connection to the specified URL and returns an object that represents this connection.

Syntax

protected abstract URLConnection openConnection(URL u) throws IOException

Parameters

u

The URL object specifying the Uniform Resource Locator to which the connection should be established.

Description

This method must be overridden in the subclass of the URLStreamHandler class that handles a specific protocol. This method should create and return an instance of a subclass of the URLConnection class that handles the connection stream to the protocol-specific data.

Imports

import java.net.URLStreamHandler;

Returns

This method returns an instance of a protocol-specific implementation of the URLConnection class. This object is used to get access to the actual data the URL points to.

See Also

The URL.getContent(URL) method

Example

Please refer to the example for the constructor method of this class.

parseURL(URL, String, int, int)

ClassName

URLStreamHandler

Purpose

Parses a string specification of a Uniform Resource Locator into the context of an existing URL object.

Syntax

protected void parseURL(URL u, String spec, int start, int limit)

Parameters

u

The URL object to use as the context for parsing the string specification (spec).

spec

A string object that specifies a Uniform Resource Locator as a text string.

start

The start index in spec at which to start the parsing.

limit

The character position in spec at which to stop parsing.

Description

The string specification spec is parsed as a URL. If it is an absolute URL, then the value of the context URL object u is set to this new URL. If the string specification is a relative path specification, then this path is parsed into u. The start parameter usually points to the character position immediately following the ':' character in a URL, and the limit index is normally the last character in the string or the position of the '#' reference mark. When a URL object is created, a URLStreamHandler object for the protocol specified in the URL is created and this method is invoked on that URLStreamHandler object.This protected method can be invoked only by the other classes in the java.net package.

Imports

import java.net.URLStreamHandler;

Returns

None. The result of the parsing is stored in the URL object u.

See Also

The URL class constructors described in this chapter

Example

This method can only be invoked by classes in the java.net package and hence no example code illustrating the usage of this method is provided here.

setURL(URL)

ClassName

URLStreamHandler

Purpose

Sets the fields of the specified URL object. This is used when a string specification is to be parsed into the context of an existing URL object.

Syntax

protected void setURL(URL u, String protocol, String host, int port, String file, String ref)

Parameters

u

The URL object that is to be modified.

protocol

The protocol (http, news, etc) to use for the URL.

host

The Internet name of the host machine.

port

The port number on the host machine.

file

The path name of the file on the host.

ref

The name of the reference that indicates a specific offset (to an anchor) into the file.

Description

This protected method is invoked by the parse(URL, String, int, int) method of this class to set the individual fields of a URL that is used as a context for parsing a string specification into.

Imports

import java.net.URLStreamHandler;

Returns

None.

See Also

The parse method of this class

Example

This method can only be invoked by classes in the java.net package and hence no example code illustrating the usage of this method is provided here.

toExternalForm(URL)

ClassName

URLStreamHandler

Purpose

Represents the specified URL object as a text string.

Syntax

protected String toExternalForm(URL u)

Parameters

u

The URL object that is to be represented as a plain text string.

Description

The specified URL object is queried to extract the individual fields (such as protocol, hostname, port, file, and reference tag) and these values are concatenated to form a text string. This text string is then returned to the invoker of this method. This is a protected method and can be accessed only by the other classes in the java.net package.

Imports

import java.net.URLStreamHandler;

Returns

This method returns a text string that represents the specified UniformResource Locator.

See Also

The toString and toExternalForm methods of the URL class, described in this chapter

URLStreamHandlerFactory

Purpose

Defines the interface that must be implemented by a class that knows how to create an instance of a specific subclass of URLStreamHandler for a specific protocol.

Syntax

public interface URLStreamHandlerFactory extends Object

Description

A class that implements this interface must know the specific subclass of URLStreamHandler that needs to be created for a protocol. As mentioned earlier in this chapter, the URLStreamHandler class needs to be subclassed to implement a URLStreamHandler for each protocol that is supported by the browser. The implementation details of constructing specific instances of the subclasses of URLStreamHandler are hidden behind this interface. Figure 11-9 shows the inheritance diagram for the URLStreamHandlerFactory interface.


Figure 11-9  Inheritance diagram for the URLStreamHandlerFactory interface

PackageName

java.net

Imports

import java.net.URLStreamHandlerFactory;

Constructors

None.

Parameters

None.

createURLStreamHandler(String)

InterfaceName

URLStreamHandlerFactory

Purpose

Creates an instance of a subclass of the URLStreamHandler class that knows how to create and handle streams for a specified protocol.

Syntax

public abstract URLStreamHandler createURLStreamHandler(String protocol)

Parameters

protocol

The protocol for which an instance of a specific subclass of the URLStreamHandler class (that handles the specified protocol) needs to be created.

Description

To implement a protocol handler in Java, you must extend the URLStreamHandler class and implement the specifics of the protocol. One of the data members of the URL class is an instance of a class that implements the URLStreamHandlerFactory interface. This data member is the same for all instances of the URL class (i.e., it is a static member) and can be set using the setURLStreamHandlerFactory method of the URL class. When you construct an URL object, the URL class invokes this method on its factory object to create an instance of the URLStreamHandler subclass that handles the protocol specified in the constructor of the URL object.

Imports

java.net.URLStreamHandlerFactory

Returns

This method returns an instance of a subclass of the URLStreamHandler object that handles the specified protocol (http, nntp, and so on).

See Also

The setURLStreamHandlerFactory of the URL class described in this chapter

Example

The following Java class implements the URLStreamHandlerFactory interface.

// File: CustomURLStreamHandlerFactory.java
// A sample implementation of a the URLStreamHandlerFactory
import java.net.*;
public class CustomURLStreamHandlerFactory implements URLStreamHandler
Factory catch (Exception e)
return handler;
}

MalformedURLException

Purpose

Signals that the specified Uniform Resource Locator (URL) is invalid.

Syntax

public class MalformedURLException extends IOException

Description

This exception is used to indicate that the URL specified is not valid. It should be used by applets to indicate that an error occurred because the specified URL was not valid. A URL that specifies an unsupported protocol is one example of a case where this exception is thrown to indicate an error in the specified protocol. Figure 11-10 shows the inheritance diagram for the MalformedURLException class.


Figure 11-10  Inheritance diagram for the MalformedURLException class

PackageName

java.net

Imports

import java.net.MalformedURLException;

Constructors

public MalformedURLException()
public MalformedURLException(String msg)

Parameters

msg

A placeholder for a message that can be used to give additional information to the user about the error that triggered this exception.

Example

The following example shows how this exception can be caught in an application.

import java.net.*;

public class TestCatchingExceptions catch (MalformedURLException e)
}

ProtocolException

Purpose

Indicates that an EPROTO error was detected when the application tried to connect to a socket.

Syntax

public class ProtocolException extends IOException

Description

This exception specifically indicates that a protocol (EPROTO) error was detected when the application tried to connect to a socket. Figure 11-11 shows the inheritance diagram for the ProtocolException class.


Figure 11-11  Inheritance diagram for the ProtocolException class

PackageName

java.net

Imports

import java.net.ProtocolException;

Constructors

public ProtocolException()
public ProtocolException(String msg)

Parameters

msg

This string can be used to give a specific description of the error that caused the ProtocolException to be thrown.

Example

The following code sample shows how you use a try/catch statement pair to catch this exception.

import java.net.ProtocolException;
.
try catch (ProtocolException e)
.

SocketException

Purpose

Indicates that an error occurred during an operation using a socket.

Syntax

public class SocketException extends IOException

Description

This exception is used to indicate errors that occur while operations are being performed on sockets. Applications may specify additional details of the error that caused this exception to be thrown in the msg parameter of the constructor for this exception. Figure 11-12 shows the inheritance diagram for the SocketException class.


Figure 11-12  Inheritance diagram for the SocketException class

PackageName

java.net

Imports

import java.net.SocketException;

Constructors

public SocketException()
public SocketException(String msg)

Parameters

msg

This string can be used to give a specific description of the error that occurred while using the socket.

Example

The following code sample shows how you use a try/catch statement pair to catch this exception.

import java.net.SocketException;
..
try catch (SocketException e)
.

UnknownHostException

Purpose

Indicates that the address of the host specified by a network client is not valid.

Syntax

public class UnknownHostException extends IOException

Description

This exception is thrown when the host address (specified by an application that is trying to connect to a server) cannot be resolved as a valid address. Applications that use the socket classes and the classes that deal with Uniform Resource Locators use this class to signal and handle error conditions. Figure 11-13 shows the inheritance diagram for the UnknownHostException class.


Figure 11-13  Inheritance diagram for the UnknownHostException class

PackageName

java.net

Imports

import java.net.UnknownHostException;

Constructors

public UnknownHostException()
public UnknownHostException(String msg)

Parameters

msg

A placeholder for a message that can be used to give additional information to the user about the error that triggered this exception.

Example

The following code sample shows how you use a try/catch statement pair to catch this exception.

import java.net.UnknownHostException;
..
try catch (UnknownHostException e)
.

UnknownServiceException

Purpose

Signals an error indicating that the requested service is not supported by the client-server protocol.

Syntax

public class UnknownServiceException extends IOException

Description

This exception is used to indicate that a particular service is not recognized by the protocol being used to effect the network transaction. This is intended primarily for use by developers of protocol handlers. Protocol handlers will extend the URLConnection class to handle specific protocols and it is in this class that this exception will be used to indicate that a service is not supported by the protocol handler. Figure 11-14 shows the inheritance diagram for the UnknownServiceException class.


Figure 11-14  Inheritance diagram for the UnknownServiceException class

PackageName

java.net

Imports

import java.net.UnknownServiceException;

Constructors

public UnknownServiceException()
public UnknownServiceException(String msg)

Parameters

msg

A placeholder for a message that can be used to give additional information to the user about the error that triggered this exception.

Example

The following code sample shows how you use a try/catch statement pair to catch this exception.

import java.net.UnknownServiceException;
..
try catch (UnknownServiceException e)
.

The URL Class Project

This applet invokes many of the methods in the URL class. By looking at this applet and running it, you will become more familiar with using the URL class. The different types of constructors for URL objects are implemented in this example and the individual fields of a URL are parsed and displayed on the screen. Data contained in the URL object is read from it and printed in the TextArea component of the URLtest applet. Figure 11-15 shows the URLtest applet in action.


Figure 11-15  The URLtest applet in action

Building the Project

This applet divides its display area into two regions. In the first region (represented by class URLPanel), the various parameters of the URL object are displayed to the user. The second region is the control panel that controls which URL's fields are displayed in the URLPanel area. The URLTestControls class implements this simple control panel.

1.  The class name for the applet is URLtest, so edit a new file named URLtest.java and type the following code into this file. (As always, you must first import the necessary java packages.)

import java.awt.*;
import java.applet.*;

import java.net.*;
import java.io.*;

2.  Now create the URLtest class which simply extends the java.applet.Applet class. It uses the BorderLayout layout manager to lay out the URLPanel and the URLTestControls objects one below the other. The event handler for this class traps the WINDOW_DESTROY event and exits if the user closes the application. It has a main method so that it can be run as an applet or as a stand-alone Java program.

public class URLtest extends Applet
public boolean handleEvent(Event e)
}
public static void main(String args[])

3.  The URLPanel displays the field parameters of the URL that was selected in the Choice box of the URLTestControls area. This class sets up labels for the fields of the URL and arranges these labels in a two-column format. A TextArea component is used to display the data read from the URL object.

class URLPanel extends Panel

5.  The next method is invoked to parse a URL string specification and display the individual field values. A URL object is created using the specified string and the individual fields of the URL are extracted using the methods of the URL class. The contents of the URL object are read and these contents are displayed in the TextArea component. An error message is printed in the TextArea if an exception was caught while reading the contents of the URL. If the specified URL string is not a valid URL then the MalformedURLException is trapped and an error message is displayed on the ErrorStatus Label component of this panel.

public void showParams(String urlString) catch (IOException ie)
} catch(MalformedURLException mue)

6.  This event handler exits if the user quits the application.

public boolean handleEvent(Event e)
}

7.  All you have left to do is put up the main control panel for this applet. The URLTestControls class is the control panel. It displays a Choice component with different URLs in it that the user can select. When a URL is selected, the fields of the URL are displayed in the URLPanel area. This class needs to notify the URLPanel whenever a selection is made, so it keeps a reference to the URLPanel object. The constructor utilizes the different forms of constructors for the URL class and adds the string representation of these URLs to the Choice box. An invalid URL specification is also added to the list of choices. This will enable you to see how exceptions are caught.

class URLTestControls extends Panel catch (MalformedURLException mue)
add(urls);
this.target.showParams('https://www.syr.edu/');

8.  When a selection is made from the list of choices, the event handler notifies the URLPanel to update the URL field parameters, as seen in the following example.

public boolean action(Event e, Object arg) else if (e.id == Event.WINDOW_DESTROY)
return false;
}

9.  That's it, you have finished creating the applet. Now save this file and compile it by typing javac URLtest.java. Then run the application by typing java URLtest.

Building the Project

This applet divides its display area into two regions. In the first region (represented by class URLPanel), the various parameters of the URL object are displayed to the user. The second region is the control panel that controls which URL's fields are displayed in the URLPanel area. The URLTestControls class implements this simple control panel.

1.  The class name for the applet is URLtest, so edit a new file named URLtest.java and type the following code into this file. (As always, you must first import the necessary java packages.)

import java.awt.*;
import java.applet.*;

import java.net.*;
import java.io.*;

2.  Now create the URLtest class which simply extends the java.applet.Applet class. It uses the BorderLayout layout manager to lay out the URLPanel and the URLTestControls objects one below the other. The event handler for this class traps the WINDOW_DESTROY event and exits if the user closes the application. It has a main method so that it can be run as an applet or as a stand-alone Java program.

public class URLtest extends Applet
public boolean handleEvent(Event e)
}
public static void main(String args[])

3.  The URLPanel displays the field parameters of the URL that was selected in the Choice box of the URLTestControls area. This class sets up labels for the fields of the URL and arranges these labels in a two-column format. A TextArea component is used to display the data read from the URL object.

class URLPanel extends Panel

5.  The next method is invoked to parse a URL string specification and display the individual field values. A URL object is created using the specified string and the individual fields of the URL are extracted using the methods of the URL class. The contents of the URL object are read and these contents are displayed in the TextArea component. An error message is printed in the TextArea if an exception was caught while reading the contents of the URL. If the specified URL string is not a valid URL then the MalformedURLException is trapped and an error message is displayed on the ErrorStatus Label component of this panel.

public void showParams(String urlString) catch (IOException ie)
} catch(MalformedURLException mue)

6.  This event handler exits if the user quits the application.

public boolean handleEvent(Event e)
}

7.  All you have left to do is put up the main control panel for this applet. The URLTestControls class is the control panel. It displays a Choice component with different URLs in it that the user can select. When a URL is selected, the fields of the URL are displayed in the URLPanel area. This class needs to notify the URLPanel whenever a selection is made, so it keeps a reference to the URLPanel object. The constructor utilizes the different forms of constructors for the URL class and adds the string representation of these URLs to the Choice box. An invalid URL specification is also added to the list of choices. This will enable you to see how exceptions are caught.

class URLTestControls extends Panel catch (MalformedURLException mue)
add(urls);
this.target.showParams('https://www.syr.edu/');

8.  When a selection is made from the list of choices, the event handler notifies the URLPanel to update the URL field parameters, as seen in the following example.

public boolean action(Event e, Object arg) else if (e.id == Event.WINDOW_DESTROY)
return false;
}

9.  That's it, you have finished creating the applet. Now save this file and compile it by typing javac URLtest.java. Then run the application by typing java URLtest.

How It Works

This project illustrates some of the methods of the URL class. These methods are applied to different URL strings and the results of these methods are displayed. This project also shows how you can use the URL class to read data from a remote URL object. Java programs written for Internet applications will find the URL class invaluable. Classes such as the ContentHandler class and the URLStreamHandler class can easily be extended to support custom data formats and protocols.These custom formats can then be viewed using the class extensions. The classes and interfaces described in this chapter provide functionality for accessing data on the Internet, and for sending to and receiving information from the World Wide Web.



Politica de confidentialitate | Termeni si conditii de utilizare



DISTRIBUIE DOCUMENTUL

Comentarii


Vizualizari: 894
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved