HttpClient 4.2, Basic Authentication, and AuthScope

21,966

Solution 1

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);

Solution 2

From at least version 4.2.3 (I guess after version 3.X), the accepted answer is no longer valid. Instead, do something like:

private HttpClient createClient() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setContentCharset(params, "UTF-8");

    Credentials credentials = new UsernamePasswordCredentials("user", "password");
    DefaultHttpClient httpclient = new DefaultHttpClient(params);
    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);

    return httpclient;
}

The JavaDoc for AuthScope.ANY says In the future versions of HttpClient the use of this parameter will be discontinued, so use it at your own risk. A better option would be to use one of the constructors defined in AuthScope.

For a discussion on how to make requests preemptive, see:

Preemptive Basic authentication with Apache HttpClient 4

Share:
21,966
user265330
Author by

user265330

Updated on February 20, 2020

Comments

  • user265330
    user265330 about 4 years

    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);