Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient 4.2, Basic Authentication, and AuthScope

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);
like image 741
user265330 Avatar asked Jun 01 '12 12:06

user265330


2 Answers

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);
like image 156
Kieran Avatar answered Sep 28 '22 02:09

Kieran


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

like image 42
Magnilex Avatar answered Sep 28 '22 01:09

Magnilex