Skip to content

Instantly share code, notes, and snippets.

@patrickbaumann
Created April 1, 2011 06:38
Show Gist options
  • Save patrickbaumann/897830 to your computer and use it in GitHub Desktop.
Save patrickbaumann/897830 to your computer and use it in GitHub Desktop.
HttpClient post authentication with cookie
import java.io.IOException;
import java.net.HttpCookie;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.junit.Test;
public class TestHttpClient extends TestCase {
@Test
public void testLogin() throws ClientProtocolException, IOException {
HttpClient h = new DefaultHttpClient();
HttpPost p = new HttpPost("http://localhost:8080/accounts/login/");
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", "username"));
nameValuePairs.add(new BasicNameValuePair("password", "password"));
p.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.ASCII));
HttpResponse r = h.execute(p);
List<HttpCookie> cookies = HttpCookie.parse(r.getFirstHeader(
"Set-Cookie").toString());
for (HttpCookie c : cookies) {
System.out.println(c.getName() + "," + c.getValue());
}
// because we're only getting one header (the sess id), this is kind of a pointless for loop
// should also grab the expiration date here
h = new DefaultHttpClient();
HttpGet get = new HttpGet("http://localhost:8080/memo/messages/");
get.setHeader("Cookie", cookies.get(0).toString());
r = h.execute(get);
assertTrue(r.getStatusLine().getStatusCode() == 200);
// this seems to pass even if not logged in. Appears HttpClient is following redirects.
// maybe there's a way to turn off redirects
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment