Wednesday, March 21, 2007

 

HttpClient code that logs in gets cookies and redirects


private void doLogin() throws Exception {
int curTestIndex = 0;
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "http");
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
PostMethod authpost = new PostMethod("/login");
// Prepare login parameters
// user=tomer&pass=1234&view=login&op=dologin&site=hhhh
NameValuePair user = new NameValuePair("user", "tomer");
NameValuePair pass = new NameValuePair("pass", "1234");
NameValuePair view = new NameValuePair("view", "login");
NameValuePair op = new NameValuePair("op", "dologin");
NameValuePair site = new NameValuePair("site", "hhhhh");
authpost.setRequestBody(
new NameValuePair[] {user, pass, view, op, site});

authpost.setRequestHeader("User-Agent", "Nokia6230i");
client.executeMethod(authpost);
System.out.println("Login form post: " + authpost.getStatusLine().toString());
// release any connection resources used by the method
authpost.releaseConnection();
// See if we got any cookies
// The only way of telling whether logon succeeded is
// by finding a session cookie
Cookie[] logoncookies = cookiespec.match(
LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies());
System.out.println("Logon cookies:");
if (logoncookies.length == 0) {
System.out.println("None");
} else {
for (int i = 0; i < logoncookies.length; i++) {
System.out.println("- " + logoncookies[i].toString());
}
}
// Usually a successful form-based login results in a redicrect to
// another url
int statuscode = authpost.getStatusCode();
if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) ||
(statuscode == HttpStatus.SC_MOVED_PERMANENTLY) ||
(statuscode == HttpStatus.SC_SEE_OTHER) ||
(statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
Header header = authpost.getResponseHeader("location");
if (header != null) {
String newuri = header.getValue();
if ((newuri == null) || (newuri.equals(""))) {
newuri = "/";
}
System.out.println("Redirect target: " + newuri);
GetMethod redirect = new GetMethod(newuri);
redirect.setFollowRedirects(true);
client.executeMethod(redirect);
System.out.println("Redirect: " + redirect.getStatusLine().toString());
// release any connection resources used by the method
System.out.println("redirect path: " + redirect.getPath());
System.out.println(redirect.getResponseBodyAsString());
redirect.releaseConnection();
} else {
System.out.println("Invalid redirect");
}
}
}

Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?