Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

612 Part II: The Java Library


Notice how the header keys and values are displayed. First, a map of the header keys and
values is obtained by callinggetHeaderFields( )(which is inherited fromURLConnection).
Next, a set of the header keys is retrieved by callingkeySet( )on the map. Then the key set
is cycled through by using a for-each styleforloop. The value associated with each key is
obtained by callingget( )on the map.

The URI Class


A relatively recent addition to Java is theURIclass, which encapsulates aUniform Resource
Identifier (URI). URIs are similar to URLs. In fact, URLs constitute a subset of URIs. A URI
represents a standard way to identify a resource. A URL also describes how to access the
resource.

Cookies


Thejava.netpackage includes classes and interfaces that help manage cookies and can be used
to create a stateful (as opposed to stateless) HTTP session. The classes areCookieHandler,
CookieManager, andHttpCookie. The interfaces areCookiePolicyandCookieStore. All but
CookieHandlerwas added by Java SE 6. (CookieHandlerwas added by JDK 5.) The creation of
a stateful HTTP session is beyond the scope of this book.

NOTEOTE For information about using cookies with servlets, see Chapter 31.


TCP/IP Server Sockets


As mentioned earlier, Java has a different socket class that must be used for creating server
applications. TheServerSocketclass is used to create servers that listen for either local or
remote client programs to connect to them on published ports.ServerSockets are quite
different from normalSockets. When you create aServerSocket, it will register itself with
the system as having an interest in client connections. The constructors forServerSocket
reflect the port number that you want to accept connections on and, optionally, how long
you want the queue for said port to be. The queue length tells the system how many client
connections it can leave pending before it should simply refuse connections. The default is


  1. The constructors might throw anIOExceptionunder adverse conditions. Here are three
    of its constructors:


Ser verSocket(intport) throws IOException Creates ser ver socket on the specified port
with a queue length of 50.
Ser verSocket(intport, intmaxQueue)
throws IOException

Creates a ser ver socket on the specified port
with a maximum queue length ofmaxQueue.
Ser verSocket(intport, intmaxQueue,
InetAddresslocalAddress)
throws IOException

Creates a ser ver socket on the specified port
with a maximum queue length ofmaxQueue.
On a multihomed host,localAddressspecifies
the IP address to which this socket binds.
Free download pdf