Apache HttpClient - User Authentication



Using HttpClient, you can connect to a website which needed username and password. This chapter explains, how to execute a client request against a site that asks for username and password.

Step 1 - Create a CredentialsProvider object

The CredentialsProvider Interface maintains a collection to hold the user login credentials. You can create its object by instantiating the BasicCredentialsProvider class, the default implementation of this interface.

CredentialsProvider credentialsPovider = new BasicCredentialsProvider();

Step 2 - Set the Credentials

You can set the required credentials to the CredentialsProvider object using the setCredentials() method.

This method accepts two objects as given below −

  • AuthScope object − Authentication scope specifying the details like hostname, port number, and authentication scheme name.

  • Credentials object − Specifying the credentials (username, password).

Set the credentials using the setCredentials() method for both host and proxy as shown below −

credsProvider.setCredentials(new AuthScope("example.com", 80), 
   new UsernamePasswordCredentials("user", "mypass"));
credsProvider.setCredentials(new AuthScope("localhost", 8000), 
   new UsernamePasswordCredentials("abc", "passwd"));

Step 3 - Create a HttpClientBuilder Object

Create a HttpClientBuilder using the custom() method of the HttpClients class.

//Creating the HttpClientBuilder
HttpClientBuilder clientbuilder = HttpClients.custom();

Step 4 - Set the credentialsPovider

You can set the above created credentialsPovider object to a HttpClientBuilder using the setDefaultCredentialsProvider() method.

Set the CredentialProvider object created in the previous step to the client builder by passing it to the CredentialsProvider object() method as shown below.

clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider);

Step 5 - Build the CloseableHttpClient

Build the CloseableHttpClient object using the build() method of the HttpClientBuilder class.

CloseableHttpClient httpclient = clientbuilder.build()

Step 6 - Create a HttpGet object and execute it

Create a HttpRequest object by instantiating the HttpGet class. Execute this request using the execute() method.

//Creating a HttpGet object
HttpGet httpget = new HttpGet("https://www.tutorialspoint.com/ ");

//Executing the Get request
HttpResponse httpresponse = httpclient.execute(httpget);

Example

Following is an example program which demonstrates the execution of a HTTP request against a target site that requires user authentication.

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
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;
import org.apache.http.impl.client.HttpClients;

public class UserAuthenticationExample {
   
   public static void main(String args[]) throws Exception{
      
      //Create an object of credentialsProvider
      CredentialsProvider credentialsPovider = new BasicCredentialsProvider();

      //Set the credentials
      AuthScope scope = new AuthScope("https://www.tutorialspoint.com/questions/", 80);
      
      Credentials credentials = new UsernamePasswordCredentials("USERNAME", "PASSWORD");
      credentialsPovider.setCredentials(scope,credentials);

      //Creating the HttpClientBuilder
      HttpClientBuilder clientbuilder = HttpClients.custom();

      //Setting the credentials
      clientbuilder = clientbuilder.setDefaultCredentialsProvider(credentialsPovider);

      //Building the CloseableHttpClient object
      CloseableHttpClient httpclient = clientbuilder.build();

      //Creating a HttpGet object
      HttpGet httpget = new HttpGet("https://www.tutorialspoint.com/questions/index.php");

      //Printing the method used
      System.out.println(httpget.getMethod()); 

      //Executing the Get request
      HttpResponse httpresponse = httpclient.execute(httpget);

      //Printing the status line
      System.out.println(httpresponse.getStatusLine());
      int statusCode = httpresponse.getStatusLine().getStatusCode();
      System.out.println(statusCode);

      Header[] headers= httpresponse.getAllHeaders();
      for (int i = 0; i<headers.length;i++) {
         System.out.println(headers[i].getName());
      }
   }
}

Output

On executing, the above program generates the following output.

GET
HTTP/1.1 200 OK
200
Advertisements