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.
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();

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.
AuthScope object − Authentication scope specifying the details like hostname, port number, and authentication scheme name.
Credentials object − Specifying the credentials (username, password).
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"));

Create a HttpClientBuilder using the custom() method of the HttpClients class.
//Creating the HttpClientBuilder
HttpClientBuilder clientbuilder = HttpClients.custom();

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);

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

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);

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());
      }
   }
}
On executing, the above program generates the following output.
GET
HTTP/1.1 200 OK
200


    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page