HttpClient 4.2, Basic Authentication, and AuthScope
apache-commons-httpclient, apache-httpclient-4.x, httpclient, java
Solution
AuthScope.ANY is what you're after: http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/auth/AuthScope.html
Try this:
final HttpClient client = new HttpClient();
client.getParams().setAuthenticationPreemptive(true);
client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user.getUsername(), user.getPassword()));
final GetMethod method = new GetMethod(uri);
client.executeMethod(method);
Problem
I have an application connecting to sites that require basic authentication. The sites are provided at run time and not known at compile time. I am using HttpClient 4.2. I am not sure if the code below is how I am supposed to specify basic authentication, but the documentation would suggest it is. However, I don't know what to pass in the constructor of `AuthScope`. I had thought that a null parameter meant that the credentials supplied should be used for all URLs, but it throws a `NullPointerException`, so clearly I am wrong. ``` m_client = new DefaultHttpClient(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(m_userName, m_password); ((DefaultHttpClient)m_client).getCredentialsProvider().setCredentials(new AuthScope((HttpHost)null), credentials); ```