Preemptive Basic authentication with Apache HttpClient 4

yossis picture yossis · Jan 6, 2010 · Viewed 71.8k times · Source

Is there an easier way to setup the http client for preemptive basic authentication than what described here?
In previous version (3.x) it used to be a simple method call (eg, httpClient.getParams().setAuthenticationPreemptive(true)).
The main thing I want to avoid is adding the BasicHttpContext to each method I execute.

Answer

Adam Batkin picture Adam Batkin · Dec 1, 2010

If you are looking to force HttpClient 4 to authenticate with a single request, the following will work:

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

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