HttpClient 4.2, Basic Authentication, and AuthScope

I have an application connecting to sites that require basic authentication. Sites are provided at runtime and are not known at compile time.

I am using HttpClient 4.2.

I'm not sure if the code below is the way I should specify basic authentication, but the documentation would suggest that it is. However, I do not know what to pass in the constructor of AuthScope . I thought a null parameter means that the provided credentials should be used for all URLs, but it throws a NullPointerException , so I'm clearly mistaken.

 m_client = new DefaultHttpClient(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(m_userName, m_password); ((DefaultHttpClient)m_client).getCredentialsProvider().setCredentials(new AuthScope((HttpHost)null), credentials); 
+6
source share
2 answers

AuthScope.ANY is what you need: http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/auth/AuthScope.html

Try the following:

  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); 
+8
source

At least version 4.2.3 (I think 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 that future versions of HttpClient will stop using this parameter, so use it at your own risk. The best option would be to use one of the constructors defined in AuthScope .

For a discussion of how to prioritize queries, see:

Proactive Basic Authentication with Apache HttpClient 4

+2
source

Source: https://habr.com/ru/post/917185/


All Articles