Apache HttpClient - Authentification des utilisateurs

En utilisant HttpClient, vous pouvez vous connecter à un site Web nécessitant un nom d'utilisateur et un mot de passe. Ce chapitre explique comment exécuter une demande client sur un site qui demande un nom d'utilisateur et un mot de passe.

Étape 1 - Créer un objet CredentialsProvider

le CredentialsProviderL'interface gère une collection pour contenir les informations de connexion de l'utilisateur. Vous pouvez créer son objet en instanciant leBasicCredentialsProvider class, l'implémentation par défaut de cette interface.

CredentialsProvider credentialsPovider = new BasicCredentialsProvider();

Étape 2 - Définissez les informations d'identification

Vous pouvez définir les informations d'identification requises pour l'objet CredentialsProvider à l'aide du setCredentials() méthode.

Cette méthode accepte deux objets comme indiqué ci-dessous -

  • AuthScope object - Portée d'authentification spécifiant les détails tels que le nom d'hôte, le numéro de port et le nom du schéma d'authentification.

  • Credentials object - Spécification des identifiants (nom d'utilisateur, mot de passe).

Définissez les informations d'identification à l'aide du setCredentials() méthode pour l'hôte et le proxy comme indiqué ci-dessous -

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

Étape 3 - Créer un objet HttpClientBuilder

Créer un HttpClientBuilder en utilisant le custom() méthode de la HttpClients classe.

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

Étape 4 - Définissez les informations d'identification

Vous pouvez définir l'objet credentialsPovider créé ci-dessus sur un HttpClientBuilder à l'aide du setDefaultCredentialsProvider() méthode.

Définissez l'objet CredentialProvider créé à l'étape précédente sur le générateur client en le transmettant au CredentialsProvider object() méthode comme indiqué ci-dessous.

clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider);

Étape 5 - Créez le CloseableHttpClient

Construisez le CloseableHttpClient objet utilisant le build() méthode de la HttpClientBuilder classe.

CloseableHttpClient httpclient = clientbuilder.build()

Étape 6 - Créez un objet HttpGet et exécutez-le

Créez un objet HttpRequest en instanciant la classe HttpGet. Exécutez cette demande en utilisant leexecute() méthode.

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

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

Exemple

Voici un exemple de programme qui montre l'exécution d'une requête HTTP sur un site cible nécessitant une authentification utilisateur.

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

Production

Lors de l'exécution, le programme ci-dessus génère la sortie suivante.

GET
HTTP/1.1 200 OK
200