W3docs

Http Basic Authentication in Java using HttpClient?

To perform HTTP basic authentication in Java using the HttpClient library, you can use the UsernamePasswordCredentials class and the BasicCredentialsProvider class.

To perform HTTP basic authentication in Java using Apache HttpClient 4.x, you can use the UsernamePasswordCredentials class and the BasicCredentialsProvider class.

First, add the required Maven dependency:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.14</version>
</dependency>

Here's an example of how you can do this:


import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

String username = "myUsername";
String password = "myPassword";

UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(AuthScope.ANY, creds);

try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
     CloseableHttpResponse response = client.execute(new HttpGet("https://example.com/protected"))) {
    int statusCode = response.getStatusLine().getStatusCode();
    // Process response...
}

This code creates an HttpClient that automatically includes the specified username and password in the Authorization header of every request. The server uses these credentials to authenticate the client.

Note that HTTP basic authentication transmits credentials in base64-encoded plaintext and should only be used over HTTPS.

I hope this helps! Let me know if you have any questions.