Sunday, March 27, 2011

HttpClient4 FORM authentication example

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

String URL = "http://localhost:8080/web/secured";


DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet(URL);

HttpResponse response = httpclient.execute(httpget);

HttpEntity entity = response.getEntity();
if (entity != null)
entity.consumeContent();

// We should get the Login Page
StatusLine statusLine = response.getStatusLine();
System.out.println("Login form get: " + statusLine);
assertEquals(200, statusLine.getStatusCode());

System.out.println("Initial set of cookies:");
List cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } // We should now login with the user name and password HttpPost httpost = new HttpPost(URL + "/j_security_check"); List nvps = new ArrayList();
nvps.add(new BasicNameValuePair("j_username", user));
nvps.add(new BasicNameValuePair("j_password", pass));

httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

response = httpclient.execute(httpost);
entity = response.getEntity();
if (entity != null)
entity.consumeContent();

statusLine = response.getStatusLine();

// Post authentication - we have a 302
assertEquals(302, statusLine.getStatusCode());
Header locationHeader = response.getFirstHeader("Location");
String location = locationHeader.getValue();

HttpGet httpGet = new HttpGet(location);
response = httpclient.execute(httpGet);

entity = response.getEntity();
if (entity != null)
entity.consumeContent();

System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}

// Either the authentication passed or failed based on the expected status code
statusLine = response.getStatusLine();
assertEquals(expectedStatusCode, statusLine.getStatusCode());
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}

No comments: