Wednesday, December 08, 2010

Apache HTTPClient 4.x Preemptive Authentication

I am using the Apache HttpClient for some work I am doing at the office. It is a really cool utility to perform web based work. A common requirement of such work is to use authentication.

The default behavior of the HttpClient is to try and connect to the resource and read the response. If the response is a 401 Unauthorized, the client sends the request again using the credentials that are set in the client. This results in an unnecessary double posting of the request. It is however compliant with RFC2616 Section 10.4.2 which describes this behavior.

In the previous version of the client (3.x), you could set the preemptive authentication with the code below:


However, version 4.x does not support this convenient arrangement. There is a more flexible arrangement using interceptors. The client supports interceptors on both the request, and the response. The use of interceptors makes the code a little more complex, but the flexibility of using multiple interceptors, and ordering them makes up for the additional code required.

I can not provide an example of my code since it was something I created for work, but here are two examples. The first is complete, and the second is simply an example.

There is an additional post on stackoverflow which indicates you may be able to use a simple addition to the header. This may work for simple clients, but it is not as flexible as the interceptor form. I have not tested the code, but have included Adam Batkin's code snippet below.

String username = ...
String password = ...
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);

HttpRequest request = ...
request.addHeader(new BasicScheme().authenticate(creds, request));


Popular Posts