Java Reference
In-Depth Information
In the MIDP world, of course, there's no web browser taking care of cookies for you. You
have to do it yourself. Fortunately, it's not very complicated.
Network code that maintains a server session ID needs to do two things:
1.
When receiving a response from a server, check for a cookie. If there is a cookie present,
save it away for later (perhaps in a member variable, record store, or file). A cookie is
just another HTTP response header line. You can check for a cookie by calling
getHeaderField() on an HttpConnection object after the request has been sent.
2.
When sending a request to the server, send the session ID cookie if it has been previ-
ously received. Again, sending a cookie to the server is just a matter of putting it in the
request headers, using HttpConnection 's setRequestProperty() method.
Each time you send a request to the server, you will be sending a session ID as a request
header. The server uses this session ID to look up a session object that can be used, server side,
to do useful stuff like retrieve preferences or maintain a shopping cart.
It's not hard to implement this behavior in a MIDlet. If you have a session ID cookie handy,
you should send it when you open up an HTTP connection to the same server, like this:
HttpConnection hc = (HttpConnection)Connector.open(url);
if (mSession != null)
hc.setRequestProperty("cookie", mSession);
This code assumes you have a session ID cookie saved away in the mSession member variable.
The first time you contact the server, of course, you won't have a session ID cookie.
Note In production code, if you save cookie in persistent storage such as a record store or file, you should
check the cookie to see if it has expired before sending it back.
Later, when you receive a response from an HTTP request, look for a cookie. If you find
one, parse out the session ID and save it away, like this:
InputStream in = hc.openInputStream();
String cookie = hc.getHeaderField("Set-cookie");
if (cookie != null) {
int semicolon = cookie.indexOf(';');
mSession = cookie.substring(0, semicolon);
}
The cookie string needs to be parsed because it comes in two pieces. The first piece contains
the cookie value: the session ID—that's the part we parse out and save. The second part
contains a cookie attribute: a path that can be used to determine when the cookie should be
sent back to the server.
For more information on the different parts of a cookie string and how they are used, see
http://www.ietf.org/rfc/rfc2965.txt and http://www.ietf.org/rfc/rfc2109.txt .
 
Search WWH ::




Custom Search