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.
Here's an example of how you can do this:
String username = "myUsername";
String password = "myPassword";
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
BasicCredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(AuthScope.ANY, creds);
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
HttpGet request = new HttpGet("http://example.com/protected");
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
This code will create an HttpClient
that includes the specified username and password in the Authorization
header of every request it sends. The server will then use these credentials to authenticate the client.
Note that HTTP basic authentication is not secure and should only be used over HTTPS.
I hope this helps! Let me know if you have any questions.