Java Reference
In-Depth Information
The login function for Recipe 8.2 is very similar to Recipe 8.1; however, cookies are
used to maintain state. This recipe makes use of the CookieUtility class to process
the cookies.
The login method begins by creating a URL object that will be used to perform the
POST.
URL url = new URL("http://www.httprecipes.com/1/8/cookie.php");
HttpURLConnection http = (HttpURLConnection) url.openConnection();
It is very important that we do not follow redirects automatically. Java is not aware of
cookies, and as a result, if Java automatically redirects, the cookie will be lost. Additionally,
since this is a POST we must call setDoOutput with true .
http.setInstanceFollowRedirects(false);
http.setDoOutput(true);
Next, the form must be posted. The user id and password are sent, along with the “Log-
in” button.
OutputStream os = http.getOutputStream();
FormUtility form = new FormUtility(os, null);
form.add("uid", uid);
form.add("pwd", pwd);
form.add("action", "Login");
form.complete();
The InputStream is not needed because we do not need to read any data from the
form. We will get the session id from the cookie attached to the response.
http.getInputStream();
cookies.loadCookies(http);
return (cookies.getMap().containsKey("hri-cookie"));
The session id is stored in a cookie named hri-cookie . This cookie will automati-
cally be applied when the search is performed. This is accomplished by the following line of
code, from the search method:
cookies.saveCookies(http);
The above method call adds the cookie headers to the HTTP request.
Summary
Sessions are a very important concept in HTTP programming. You cannot access data
from many websites until you have logged on. Logging onto a website establishes a session.
To work with such web sites, your bot must support sessions. There are two ways that web
sites commonly support sessions: in the URL variables and in cookies.
Search WWH ::




Custom Search