Chapter 16. The java.net PackageThe java.net package provides a powerful and flexible infrastructure for networking. Figure 16-1 and Figure 16-2 show the class hierarchy for this package. Many of the classes in this package are part of the networking infrastructure and are not used by normal applications; these complicated classes can make the package a difficult one to understand. In this overview, I describe only the classes an application might normally use. Figure 16-1. The classes of the java.net packageFigure 16-2. The exceptions of the java.net packageThe URL class represents an Internet uniform resource locator (URL). It provides a very simple interface to networking: the object referred to by the URL can be downloaded with a single call, or streams may be opened to read from or write to the object. At a slightly more complex level, a URLConnection object can be obtained from a given URL object. The URLConnection class provides additional methods that allow you to work with URLs in more sophisticated ways. If you want to do more than simply download an object referenced by a URL, you can do your own networking with the Socket class. This class allows you to connect to a specified port on a specified Internet host and read and write data using the InputStream and OutputStream classes of the java.io package. If you want to implement a server to accept connections from clients, you can use the related ServerSocket class. Both Socket and ServerSocket use the InetAddress address class, which represents an Internet address. The java.net package allows you to do low-level networking with DatagramPacket objects, which may be sent and received over the network through a DatagramSocket object. As of Java 1.1, the package has been extended to include a MulticastSocket class that supports multicast networking.
This abstract class defines a customizable mechanism for requesting and performing password authentication. The static setDefault() method establishes the systemwide Authenticator object to use when password authentication is requested. The implementation can obtain the required authentication information from the user however it wants (e.g., through a text- or a GUI-based interface). setDefault() can be called only once; subsequent calls are ignored. Calling setDefault() requires an appropriate NetPermission. When an application or the Java runtime system requires password authentication (to read the contents of a specified URL, for example), it calls the static requestPasswordAuthentication() method, passing arguments that specify the host and port for which the password is required and a prompt that may be displayed to the user. This method looks up the default Authenticator for the system and calls its getPasswordAuthentication() method. Calling requestPasswordAuthentication() requires an appropriate NetPermission. Authenticator is an abstract class; its default implementation of getPasswordAuthentication() always returns null. To create an Authenticator, you must override this method so that it prompts the user to enter a username and password and returns that information in the form of a PasswordAuthentication object. Your implementation of getPasswordAuthentication() may call the various getRequesting() methods to find who is requesting the password and what the recommended user prompt is.
Passed To: Authenticator.setDefault()
Signals that a socket cannot be bound to a local address and port. This often means that the port is already in use.
Hierarchy: Object-->Throwable(Serializable)-->Exception-->java.io.IOException-->SocketException-->BindException
Signals that a socket cannot be connected to a remote address and port. This means that the remote host can be reached, but is not responding, perhaps because there is no process on that host that is listening on the specified port.
Hierarchy: Object-->Throwable(Serializable)-->Exception-->java.io.IOException-->SocketException-->java.net.ConnectException
This abstract class defines a method that reads data from a URLConnection and returns an object that represents that data. Each subclass that implements this method is responsible for handling a different type of content (i.e., a different MIME type). Applications never create ContentHandler objects directly; they are created, when necessary, by the registered ContentHandlerFactory object. Applications should also never call ContentHandler methods directly; they should call URL.getContent() or URLConnection.getContent() instead. You need to subclass ContentHandler only if you are writing a web browser or similar application that needs to parse and understand some new content type.
Returned By: ContentHandlerFactory.createContentHandler()
This interface defines a method that creates and returns an appropriate ContentHandler object for a specified MIME type. A systemwide ContentHandlerFactory interface may be specified using the URLConnection.setContentHandlerFactory() method. Normal applications never need to use or implement this interface.
Passed To: URLConnection.setContentHandlerFactory()
This class implements a packet of data that may be sent or received over the network through a DatagramSocket. One of the DatagramPacket constructors specifies an array of binary data to be sent with its destination address and port. A packet created with this constructor can then be sent with the send() method of a DatagramSocket. The other DatagramPacket constructor specifies an array of bytes into which data should be received. The receive() method of DatagramSocket waits for data and stores it in a DatagramPacket created in this way. The contents and sender of a received packet can be queried with the DatagramPacket instance methods.
Passed To: DatagramSocket.{receive(), send()}, DatagramSocketImpl.{receive(), send()}, MulticastSocket.send()
This class defines a socket that can receive and send unreliable datagram packets over the network using the UDP protocol. A datagram is a very low-level networking interface: it is simply an array of bytes sent over the network. A datagram does not implement any kind of stream-based communication protocol, and there is no connection established between the sender and the receiver. Datagram packets are called "unreliable" because the protocol does not make any attempt to ensure they arrive or to resend them if they don't. Thus, packets sent through a DatagramSocket are not guaranteed to arrive in the order sent or even to arrive at all. On the other hand, this low-overhead protocol makes datagram transmission very fast. See Socket and URL for higher-level interfaces to networking. If a port is specified when the DatagramSocket is created, that port is used for sending and receiving datagrams; otherwise, the system assigns a port. getLocalPort() returns the port number in use. send() sends a DatagramPacket through the socket. The packet must contain the destination address to which it should be sent. receive() waits for data to arrive at the socket and stores it, along with the address of the sender, in the specified DatagramPacket. close() closes the socket and frees the port for reuse. Once close() has been called, the DatagramSocket should not be used again. Each time a packet is sent or received, the system must perform a security check to ensure that the calling code has permission to send data to or receive data from the specified host. In Java 1.2 and later, if you are sending multiple packets to or receiving multiple packets from a single host, use connect() to specify the host with which you are communicating. This causes the security check to be done a single time, but does not allow the socket to communicate with any other host until disconnect() is called. Use getInetAddress() and getPort() to obtain the host and port, if any, the socket is connected to. setSoTimeout() specifies the number of milliseconds that receive() waits for a packet to arrive before throwing an InterruptedIOException. Specify 0 milliseconds to wait forever. setSendBufferSize() and setReceiveBufferSize() set hints as to the underlying size of the networking buffers.
Subclasses: MulticastSocket
This abstract class defines the methods necessary to implement communication through datagram and multicast sockets. System programmers may create subclasses of this class when they need to implement datagram or multicast sockets in a nonstandard network environment, such as behind a firewall or on a network that uses a nonstandard transport protocol. Normal applications never need to use or subclass this class.
Hierarchy: Object-->DatagramSocketImpl(SocketOptions) Returned By: DatagramSocketImplFactory.createDatagramSocketImpl()
This interface defines a method that creates DatagramSocketImpl objects. You can register an instance of this factory interface with the static setDatagramSocketImplFactory() method of DatagramSocket. Application-level code never needs to use or implement this interface.
Passed To: DatagramSocket.setDatagramSocketImplFactory()
This interface defines a single method that is called to obtain the MIME type of a file based on the name of the file. The fileNameMap field of the URLConnection class refers to an object that implements this interface. The filename-to-file-type map it implements is used by the static URLConnection.guessContentTypeFromName() method.
Passed To: URLConnection.setFileNameMap() Returned By: URLConnection.getFileNameMap()
This class is a specialization of URLConnection. An instance of this class is returned when the openConnection() method is called for a URL object that uses the HTTP protocol. The many constants defined by this class are the status codes returned by HTTP servers. setRequestMethod() specifies what kind of HTTP request is made. The contents of this request must be sent through the OutputStream returned by the getOutputStream() method of the superclass. Once an HTTP request has been sent, getResponseCode() returns the HTTP server's response code as an integer, and getResponseMessage() returns the server's response message. The disconnect() method closes the connection. The static setFollowRedirects() specifies whether URL connections that use the HTTP protocol should automatically follow redirect responses sent by HTTP servers. In order to successfully use this class, you need to understand the details of the HTTP protocol.
Hierarchy: Object-->URLConnection-->HttpURLConnection
This class represents an Internet address and is used when creating DatagramPacket or Socket objects. The class does not have a public constructor function, but instead supports three static methods that return one or more instances of InetAddress. getLocalHost() returns an InetAddress for the local host. getByName() returns the InetAddress of a host specified by name. getAllByName() returns an array of InetAddress objects that represents all the available addresses for a host specified by name. Instance methods are getHostName(), which returns the hostname of an InetAddress, and getAddress(), which returns the Internet IP address as an array of bytes, with the highest-order byte as the first element of the array.
Hierarchy: Object-->InetAddress(Serializable) Passed To: Too many methods to list. Returned By: Authenticator.getRequestingSite(), DatagramPacket.getAddress(), DatagramSocket.{getInetAddress(), getLocalAddress()}, InetAddress.{getAllByName(), getByName(), getLocalHost()}, MulticastSocket.getInterface(), ServerSocket.getInetAddress(), Socket.{getInetAddress(), getLocalAddress()}, SocketImpl.getInetAddress(), URLStreamHandler.getHostAddress() Type Of: SocketImpl.address
This class is a specialized URLConnection that represents a connection to a jar: URL. A jar: URL is a compound URL that includes the URL of a JAR archive and, optionally, a reference to a file or directory within the JAR archive. The jar: URL syntax uses the ! character to separate the pathname of the JAR archive from the filename within the JAR archive. Note that a jar: URL contains a subprotocol that specifies the protocol that retrieves the JAR file itself. For example: jar:http://my.jar.com/my.jar!/ // The whole archive jar:file:/usr/java/lib/my.jar!/com/jar/ // A directory of the archive jar:ftp://ftp.jar.com/pub/my.jar!/com/jar/Jar.class // A file in the archive To obtain a JarURLConnection, define a URL object for a jar: URL, open a connection to it with openConnection(), and cast the returned URLConnection object to a JarURLConnection. The various methods defined by JarURLConnection allow you to read the manifest file of the JAR archive and look up attributes from that manifest for the archive as a whole or for individual entries in the archive. These methods make use of various classes from the java.util.jar package.
Hierarchy: Object-->URLConnection-->JarURLConnection
Signals that an unparseable URL specification has been passed to a method.
Hierarchy: Object-->Throwable(Serializable)-->Exception-->java.io.IOException-->MalformedURLException Thrown By: Too many methods to list.
This subclass of DatagramSocket can send and receive multicast UDP packets. It extends DatagramSocket by adding joinGroup() and leaveGroup() methods to join and leave multicast groups. The IP address specified to these methods should be a valid multicast address in the range of 224.0.0.1 to 239.255.255.255. Note that you do not have to join a group to send a packet to a multicast address, but you must join the group to receive packets sent to that address. Note that untrusted code is not allowed to use multicast sockets. MulticastSocket defines a variant send() method that allows you to specify a time-to-live (TTL) value for the packet you send. This value specifies the number of network hops the packet can travel before it expires. You can also set a default TTL for all packets sent though a MulticastSocket with setTimeToLive(), or, prior to Java 1.2, with setTTL().
Hierarchy: Object-->DatagramSocket-->MulticastSocket
This class is a java.security.Permission that represents various permissions required for Java's URL-based networking system. See also SocketPermission, which represents permissions to perform lower-level networking operations. A NetPermission is defined solely by its name; no actions list is required or supported. As of Java 1.2, there are three NetPermission targets defined: "setDefaultAuthenticator" is required to call Authenticator.setDefault(); "requestPasswordAuthentication" to call Authenticator.requestPasswordAuthentication(); and "specifyStreamHandler" to explicitly pass a URLStreamHandler object to the URL() constructor. The target "*" is a wildcard that represents all defined NetPermission targets. System administrators configuring security policies must be familiar with this class and the permissions it represents. System programmers may use this class, but application programmers never need to use it explicitly.
Hierarchy: Object-->java.security.Permission(java.security.Guard,Serializable)-->java.security.BasicPermission(Serializable)-->NetPermission
This exception signals that a socket cannot be connected to a remote host because the host cannot be contacted. Typically, this means that some link in the network between the local machine and the remote host is down or that the host is behind a firewall.
Hierarchy: Object-->Throwable(Serializable)-->Exception-->java.io.IOException-->SocketException-->NoRouteToHostException
This simple immutable class encapsulates a username and a password. The password is stored as a character array rather than as a String object so that the caller can erase the contents of the array after use for increased security. Note that the PasswordAuthentication() constructor clones the specified password character array, but getPassword() returns a reference to the object's internal array. Obtain a PasswordAuthentication object by calling Authenticator.requestPasswordAuthentication().
Returned By: Authenticator.{getPasswordAuthentication(), requestPasswordAuthentication()}
Signals a protocol error in the Socket class.
Hierarchy: Object-->Throwable(Serializable)-->Exception-->java.io.IOException-->ProtocolException Thrown By: HttpURLConnection.setRequestMethod()
This class is used by servers to listen for connection requests from clients. When you create a ServerSocket, you specify the port to listen on. The accept() method begins listening on that port and blocks until a client requests a connection on the port. At that point, accept() accepts the connection, creating and returning a Socket the server can use to communicate with the client. A typical server starts a new thread to handle the communication with the client and calls accept() again to listen for another connection. If you do not want accept() to block for an indefinite amount of time, call setSoTimeout() to specify the number of milliseconds accept() should wait for a connection before throwing an InterruptedIOException.
Returned By: java.rmi.server.RMIServerSocketFactory.createServerSocket(), java.rmi.server.RMISocketFactory.createServerSocket()
This class implements a socket for stream-based interprocess communication over the network. See URL for a higher-level interface to networking and DatagramSocket for a lower-level interface. Use the Socket() constructor to create a socket and connect it to the specified host and port. Once the socket is created, getInputStream() and getOutputStream() return InputStream and OutputStream objects you can use to communicate with the remote host, just as you would use them for file input and output. getInetAddress() and getPort() return the address and port to which the socket is connected. getLocalPort() returns the local port the socket is using. See ServerSocket for information about how a server can listen for and accept connections of this type. When you are done with a Socket, use close() to close it. In Java 1.3, you can also use shutdownInput() and shutdownOutput() to close the input and output communication channels individually. There are several options you can specify for a Socket object to alter its behavior. setSendBufferSize() and setReceiveBufferSize() provide hints to the underlying networking system as to what buffer size is best to use with this socket. setSoTimeout() specifies the number of milliseconds a read() call on the input stream returned by getInputStream() waits for data before throwing an InterruptedIOException. The default value of 0 specifies that the stream blocks indefinitely. setSoLinger() specifies what to do when a socket is closed while there is still data waiting to be transmitted. If lingering is turned on, the close() call blocks for up to the specified number of seconds while attempting to transmit the remaining data. Calling setTcpNoDelay() with an argument of true causes data to be sent through the socket as soon as it is available, instead of waiting for the TCP packet to become more full before sending it. In Java 1.3, use setKeepAlive() to enable or disable the periodic exchange of control messages across an idle socket connection. The keepalive protocol enables a client to determine if its server has crashed without closing the socket and vice versa.
Passed To: ServerSocket.implAccept() Returned By: ServerSocket.accept(), java.rmi.server.RMIClientSocketFactory.createSocket(), java.rmi.server.RMISocketFactory.createSocket()
Signals an exceptional condition while using a socket.
Hierarchy: Object-->Throwable(Serializable)-->Exception-->java.io.IOException-->SocketException Subclasses: BindException, java.net.ConnectException, NoRouteToHostException Thrown By: Too many methods to list.
This abstract class defines the methods necessary to implement communication through sockets. Different subclasses of this class may provide different implementations suitable in different environments (such as behind firewalls). These socket implementations are used by the Socket and ServerSocket classes. Normal applications never need to use or subclass this class.
Hierarchy: Object-->SocketImpl(SocketOptions) Passed To: Socket.Socket(), SocketImpl.accept() Returned By: SocketImplFactory.createSocketImpl()
This interface defines a method that creates SocketImpl objects. SocketImplFactory objects may be registered to create SocketImpl objects for the Socket and ServerSocket classes. Normal applications never need to use or implement this interface.
Passed To: ServerSocket.setSocketFactory(), Socket.setSocketImplFactory()
This interface defines constants that represent low-level BSD Unix-style socket options and methods that set and query the value of those options. In Java 1.2, SocketImpl and DatagramSocketImpl implement this interface. Any custom socket implementations you define should also provide meaningful implementations for the getOption() and setOption() methods. Your implementation may support options other than those defined here. Only custom socket implementations need to use this interface. All other code can use methods defined by Socket, ServerSocket, DatagramSocket, and MulticastSocket to set specific socket options for those socket types.
Implementations: DatagramSocketImpl, SocketImpl
This class is a java.security.Permission that governs all networking operations performed with sockets. Like all permissions, a SocketPermission consists of a name, or target, and a list of actions that may be performed on that target. The target of a SocketPermission is the host and, optionally, the port or ports for which permission is being granted or requested. The target consists of a hostname optionally followed by a colon and a port specification. The host may be a DNS domain name, a numerical IP address, or the string "localhost". If you specify a host domain name, you may use * as a wildcard as the leftmost portion of the hostname. The port specification, if present, must be a single port number or a range of port numbers in the form n1-n2. If n1 is omitted, it is taken to be 0, and if n2 is omitted, it is taken to be 65535. If no port is specified, the socket permission applies to all ports of the specified host. Here are some legal SocketPermission targets: java.sun.com:80 *.sun.com:1024-2000 *:1024- localhost:-1023 In addition to a target, each SocketPermission must have a comma-separated list of actions, which specify the operations that may be performed on the specified host(s) and port(s). The available actions are "connect", "accept", "listen", and "resolve". "connect" represents permission to connect to the specified target. "accept" indicates permission to accept connections from the specified target. "listen" represents permission to listen on the specified ports for connection requests. This action is only valid when used for ports on "localhost". Finally, the "resolve" action indicates permission to use the DNS name service to resolve domain names into IP addresses. This action is required for and implied by all other actions. System administrators configuring security policies must be familiar with this class and understand the risks of granting the various permissions it represents. System programmers writing new low-level networking libraries or connecting to native code that performs networking may need to use this class. Application programmers, however, should never need to use it directly.
Hierarchy: Object-->java.security.Permission(java.security.Guard,Serializable)-->SocketPermission(Serializable)
Signals that the name of a specified host could not be resolved.
Hierarchy: Object-->Throwable(Serializable)-->Exception-->java.io.IOException-->java.net.UnknownHostException Thrown By: InetAddress.{getAllByName(), getByName(), getLocalHost()}, Socket.Socket()
Signals an attempt to use an unsupported service of a network connection.
Hierarchy: Object-->Throwable(Serializable)-->Exception-->java.io.IOException-->UnknownServiceException
This class represents a uniform resource locator and allows the data referred to by the URL to be downloaded. A URL can be specified as a single string or with separate protocol, host, port, and file specifications. Relative URLs can also be specified with a String and the URL object to which it is relative. getFile(), getHost(), getPort(), getProtocol(), and getRef() return the various portions of the URL specified by a URL object. sameFile() determines whether a URL object refers to the same file as this one. The data or object referred to by a URL can be downloaded from the Internet in three ways: with a URLConnection created with openConnection(), with an InputStream created by openStream(), or with getContent(), which returns the URL contents directly if an appropriate ContentHandler can be found.
Hierarchy: Object-->URL(Serializable) Passed To: Too many methods to list. Returned By: Too many methods to list. Type Of: URLConnection.url
This ClassLoader provides a useful way to load untrusted Java code from a search path of arbitrary URLs, where each URL represents a directory or JAR file to search. Use the inherited loadClass() method to load a named class with a URLClassLoader. Classes loaded by a URLClassLoader have whatever permissions are granted to their java.security.CodeSource by the system java.security.Policy, plus they have one additional permission that allows the class loader to read any resource files associated with the class. If the class is loaded from a local file: URL that represents a directory, the class is given permission to read all files and directories below that directory. If the class is loaded from a local file: URL that represents a JAR file, the class is given permission to read that JAR file. If the class is loaded from a URL that represents a resource on another host, that class is given permission to connect to and accept network connections from that host. Note, however, that loaded classes are not granted this additional permission if the code that created the URLClassLoader in the first place would not have had that permission. You can obtain a URLClassLoader by calling one of the URLClassLoader() constructors or one of the static newInstance() methods. If you call newInstance(), the loadClass() method of the returned URLClassLoader performs an additional check to ensure that the caller has permission to access the specified package.
Hierarchy: Object-->ClassLoader-->java.security.SecureClassLoader-->URLClassLoader Returned By: URLClassLoader.newInstance()
This abstract class defines a network connection to an object specified by a URL. URL.openConnection() returns a URLConnection instance. You should use a URLConnection object when you want more control over the downloading of data than is available through the simpler URL methods. connect() actually makes the network connection. Other methods that depend on being connected call this method. getContent() returns the data referred to by the URL, parsed into an appropriate type of Object. If the URL protocol supports read and write operations, getInputStream() and getOutputStream() return input and output streams to the object referred to by the URL, respectively. getContentLength(), getContentType(), getContentEncoding(), getExpiration(), getDate(), and getLastModified() return the appropriate information about the object referred to by the URL, if that information can be determined (e.g., from HTTP header fields). getHeaderField() returns an HTTP header field specified by name or by number. getHeaderFieldInt() and getHeaderFieldDate() return the value of a named header field parsed as an integer or a date. There are a number of options you can specify to control how the URLConnection behaves. These options are set with the various set() methods and may be queried with corresponding get() methods. The options must be set before the connect() method is called. setDoInput() and setDoOutput() allow you to specify whether you are using the URLConnection for input and/or output (input-only by default). setAllowUserInteraction() specifies whether user interaction (such as typing a password) is allowed during the data transfer (false by default). setDefaultAllowUserInteraction() is a class method that allows you to change the default value for user interaction. setUseCaches() allows you to specify whether a cached version of the URL can be used. You can set this to false to force a URL to be reloaded. setDefaultUseCaches() sets the default value for setUseCaches(). setIfModifiedSince() allows you to specify that a URL should not be fetched unless it has been modified since a specified time (if it is possible to determine its modification date).
Subclasses: HttpURLConnection, JarURLConnection Passed To: ContentHandler.getContent() Returned By: URL.openConnection(), URLStreamHandler.openConnection() Type Of: JarURLConnection.jarFileURLConnection
This class defines a static decode() method that reverses the encoding performed by URLEncoder.encode(). It decodes 8-bit text with the MIME type "x-www-form-urlencoded", which is a standard encoding used by web browsers to submit form contents to CGI scripts and other server-side programs.
This class defines a single static method that converts a string to its URL-encoded form. That is, spaces are converted to +, and nonalphanumeric characters other than underscore are output as two hexadecimal digits following a percent sign. Note that this technique works only for 8-bit characters. This method canonicalizes a URL specification so that it uses only characters from an extremely portable subset of ASCII that can be correctly handled by computers around the world.
This abstract class defines the openConnection() method that creates a URLConnection for a given URL. A separate subclass of this class may be defined for various URL protocol types. A URLStreamHandler is created by a URLStreamHandlerFactory. Normal applications never need to use or subclass this class.
Passed To: URL.URL() Returned By: URLStreamHandlerFactory.createURLStreamHandler()
This interface defines a method that creates a URLStreamHandler object for a specified protocol. Normal applications never need to use or implement this interface.
Passed To: URL.setURLStreamHandlerFactory(), URLClassLoader.URLClassLoader() Copyright © 2001 O'Reilly & Associates. All rights reserved. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|