Java Reference
In-Depth Information
{
System.out.println(item);
}
If
null
was returned as the session id, then the login failed. The user id or password
were likely incorrect.
} else
{
System.out.println("Error logging in.");
}
The
process
method makes use of both the
login
function and the
search
func-
tion. The next two sections will describe how these functions work.
Logging In
The login method is responsible for logging the user into the system and returning a ses-
sion id. This method begins by posting the user id and password to the web site. To do this, a
URL object is constructed to post to the login form. Since this will be a post,
setDoOutput
must be called.
URL url =
new URL("http://www.httprecipes.com/1/8/cookieless.php");
URLConnection http = url.openConnection();
http.setDoOutput(true);
Next, an
OutputStream
is obtained to post the data to. This
OutputStream
is passed to the constructor of the
FormUtility
class. Then the user id, password and
login button are all added to the form. Since submit buttons can also send data to the form, it
is important to designate that the Login button is used here.
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 whatever page the login form redirects us to.
http.getInputStream();
String query = http.getURL().getQuery();
If there is no query string on the URL, then the login failed, and we should return
null
. Otherwise, we call the
parse
method of the
FormUtility
class to extract the
session
attribute from the URL. The
session
attribute contains the session id.
if (query != null)