Friday, January 28, 2011

Basic Authentication with Apache HttpClient

This is the general idiom used for BASIC authentication with Apache's HttpClient, version 3.1. We don't bother with additional cruft needed for SSL connections, just the minimum naive snippet:


HttpClient httpClient = new HttpClient();
httpClient.getParams().setAuthenticationPreemptive(true);
Credentials creds = new UsernamePasswordCredentials("user", "password");
httpClient.getState().setCredentials(new AuthScope("www.mybiz.com", 8080, AuthScope.ANY_REALM), creds);
GetMethod request = new GetMethod(ssgURL);
request.setDoAuthentication(true);
try {
try {
int status = httpClient.executeMethod(request);
if (status != 200) {
String response = request.getResponseBodyAsString();
throw new IllegalStateException("Status " + status + ":" + response);
}
// else, do something useful
} catch (IOException e) {
throw new IllegalStateException(e);
}
} finally {
request.releaseConnection();
}

1 comment:

  1. Finally! An example that works. I think the setAuthenticationPreemptive(true); did it for me. Thanks!

    ReplyDelete