Apache HttpClient Basic Authentication Examples

Introduction

Apache HttpClient is a versatile and powerful library for handling HTTP requests in Java. It supports various authentication mechanisms, including Basic Authentication. Basic Authentication is a simple authentication scheme built into the HTTP protocol. It uses a username and password to authenticate requests. This tutorial will demonstrate how to use Apache HttpClient to make HTTP requests with Basic Authentication.

Maven Dependencies

To use Apache HttpClient, you need to add the following dependency to your pom.xml file:

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents.client5/httpclient5 -->
<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.3</version>
</dependency>

Example Scenario

We will create a simple Java class that sends a GET request to a specified URL with Basic Authentication and prints the response.

Sample API for Testing

For demonstration purposes, we'll use a mock API endpoint that requires Basic Authentication. However, since this is an example, you can replace the URL, username, and password with any valid endpoint that supports Basic Authentication.

Java Class for Sending HTTP Request with Basic Authentication

Create a class named HttpClientBasicAuthExample with the following code:

import org.apache.hc.client5.http.auth.Credentials;
import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.CloseableHttpResponse;
import org.apache.hc.core5.http.io.entity.EntityUtils;

public class HttpClientBasicAuthExample {

    public static void main(String[] args) {
        String url = "https://httpbin.org/basic-auth/user/pass";
        String username = "user";
        String password = "pass";

        // Create the CredentialsProvider
        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        Credentials credentials = new UsernamePasswordCredentials(username, password.toCharArray());
        credentialsProvider.setCredentials(null, credentials);

        // Create HttpClient with the CredentialsProvider
        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCredentialsProvider(credentialsProvider)
                .build()) {

            // Create HttpGet request
            HttpGet request = new HttpGet(url);

            // Execute the request
            try (CloseableHttpResponse response = httpClient.execute(request)) {

                // Get HttpResponse Status
                System.out.println("Response Code: " + response.getCode());

                // Get HttpResponse Content
                String content = EntityUtils.toString(response.getEntity());
                System.out.println("Response Content: \n" + content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation

  1. Adding Maven Dependencies:

    • The org.apache.httpcomponents.client5:httpclient5 dependency provides the classes needed to create and execute HTTP requests using Apache HttpClient.
  2. Creating CredentialsProvider:

    • BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); creates an instance of BasicCredentialsProvider which will hold the credentials.
    • Credentials credentials = new UsernamePasswordCredentials(username, password.toCharArray()); creates an instance of UsernamePasswordCredentials with the specified username and password.
    • credentialsProvider.setCredentials(null, credentials); sets the credentials in the credentials provider.
  3. Creating HttpClient:

    • CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build(); creates an instance of CloseableHttpClient using the custom configuration with the credentials provider.
  4. Creating HttpGet Request:

    • HttpGet request = new HttpGet(url); creates an HttpGet request for the specified URL.
  5. Executing the Request:

    • try (CloseableHttpResponse response = httpClient.execute(request)) { ... } executes the GET request and retrieves the response.
  6. Getting HttpResponse Status:

    • System.out.println("Response Code: " + response.getCode()); prints the status code of the HTTP response.
  7. Getting HttpResponse Content:

    • String content = EntityUtils.toString(response.getEntity()); converts the response entity to a string and prints the content.

Running the Example

To run the example, simply execute the HttpClientBasicAuthExample class. You should see the status code and the content of the response printed in the console.

Example Output

Response Code: 200
Response Content: 
{
  "authenticated": true,
  "user": "user"
}

Additional Configuration

Setting Custom Headers

You can set custom headers for the GET request by using the setHeader method on the HttpGet object.

request.setHeader("User-Agent", "Mozilla/5.0");

Handling Redirects

By default, Apache HttpClient handles redirects automatically. You can customize this behavior by using a custom HttpClientBuilder.

CloseableHttpClient httpClient = HttpClients.custom()
    .setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        protected boolean isRedirectable(String method) {
            return true;
        }
    })
    .build();

Setting Timeouts

You can set connection and socket timeouts by using RequestConfig.

RequestConfig requestConfig = RequestConfig.custom()
    .setConnectTimeout(5000)
    .setSocketTimeout(5000)
    .build();

HttpGet request = new HttpGet(url);
request.setConfig(requestConfig);

Conclusion

Using Apache HttpClient to make HTTP requests with Basic Authentication is straightforward and flexible. By following this tutorial, you should now be able to create and execute GET requests with Basic Authentication, handle responses, and customize various aspects of the HTTP request and response process. Apache HttpClient provides a comprehensive set of features that make it an excellent choice for handling HTTP operations in Java applications. The sample API endpoint serves as a practical and convenient source for testing and prototyping your HTTP requests.

Comments