Apache HttpClient (4.1 and newer): how to do basic authentication?

Pablo picture Pablo · Feb 22, 2012 · Viewed 78.7k times · Source

How do I add basic authentication for the default client of the httpClient library? I have seen examples where they use client.getCredentialProvider(), however I think all of this methods are for library version 4.0.1 or 3.x. Is there a new example of how to do this? Thanks a lot.

Answer

Joe picture Joe · Feb 24, 2014
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, 
    new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpClient = 
    HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();