6.3 Session Tracking via HTTP CookiesCookies are pieces of NAME=VALUE formatted text embedded in HTTP headers. They are used to track client states. Since cookies reside in HTTP headers, they are transparent to applications and users. The server assigns new cookies to the client through the HTTP header set-cookie. The set-cookie header takes the following format:
The first NAME=VALUE is the cookie itself and is required. All the following attributes, such as expiration time, domain, and path, are optional. When the client makes subsequent requests, it sends the cookies back in the cookies header to identify itself.
NoteThe server can send out multiple cookies in one connection using multiple set-cookie headers. The client can send back multiple cookies in one header by delimiting them using semicolons.6.3.1 Handle Cookies via Decorator ClassesSun Microsystems' Smart Ticket blueprint v1.1 provides a class SessionConnector that utilizes the decorator pattern to add cookie support into the standard MIDP HTTP framework. The source code of this class is available from this book's Web site. The following snippet demonstrates how to use this class.
6.3.2 Handle Cookies via HttpClient HandlersTo support cookie headers in the HttpClient framework, we need to write the handler class. The source code of handler class (CookieHandler) is shown in Listing 6.4. Method getCookie() parses the response header and stores cookies in a static data member cookies. Method addCookie() matches stored cookies with the current request URL to determine which cookies to send out. Please refer to this book's Web site for complete source code. Listing 6.4. The CookieHandler class
The use of CookieHandler is illustrated in Listing 6.5. Listing 6.5. The CookieHandler usage
|