HttpClient用户身份验证

使用HttpClient,您可以连接到需要用户名和密码的网站。本章介绍如何针对要求输入用户名和密码的站点执行客户端请求。

第1步 - 创建CredentialsProvider对象
CredentialsProvider接口维护一个集合以保存用户登录凭据。可以通过实例化BasicCredentialsProvider类(此接口的默认实现)来创建其对象。

CredentialsProvider credentialsPovider = new BasicCredentialsProvider();

Java

第2步 - 设置凭据

可以使用setCredentials()方法将所需凭据设置为CredentialsProvider对象。

此方法接受以下给出的两个对象 -

  • AuthScope对象 - 验证范围,指定主机名,端口号和验证方案名称等详细信息。
  • Credentials对象 - 指定凭据(用户名,密码)。

使用setCredentials()方法为主机和代理设置凭据,如下所示 -

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

Java

第3步 - 创建HttpClientBuilder对象

使用HttpClients类的custom()方法创建HttpClientBuilder

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

Java

第4步 - 设置credentialsPovider
可以使用setDefaultCredentialsProvider()方法将上面创建的credentialsPovider对象设置为HttpClientBuilder

将上一步中创建的CredentialProvider对象设置为客户端构建器,方法是将其传递给CredentialsProvider object()方法,如下所示。

clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider);

Java

第5步 - 构建CloseableHttpClient

使用HttpClientBuilder类的build()方法构建CloseableHttpClient对象。

CloseableHttpClient httpclient = clientbuilder.build();

Java

第6步 - 创建一个HttpGet对象并执行它
通过实例化HttpGet类来创建HttpRequest对象。使用execute()方法执行此请求。

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

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

Java

示例
以下是一个示例程序,演示了针对需要用户身份验证的目标站点执行HTTP请求。

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.kaops.com/", 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.kaops.com/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());
      }
   }
}

Java

执行上面示例代码,得到以下结果:

GET
HTTP/1.1 200 OK
200

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Apache HttpClient是一个非常流行的Java HTTP客户端库。它支持基本身份验证Basic Authentication),该身份验证方案要求用户提供用户名和密码以访问受保护的资源。 以下是一个使用Apache HttpClient进行基本身份验证的示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; 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.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class BasicAuthExample { public static void main(String[] args) throws IOException { // 创建 HttpClient 实例 CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( // 认证范围 new AuthScope("localhost", 8080), // 认证凭据 new UsernamePasswordCredentials("username", "password")); CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credsProvider) .build(); try { // 创建 HttpGet 请求 HttpHost target = new HttpHost("localhost", 8080, "http"); HttpGet httpget = new HttpGet("/"); System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target); // 执行请求 CloseableHttpResponse response = httpclient.execute(target, httpget); try { // 获取响应实体 HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); System.out.println(EntityUtils.toString(entity)); } EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } } } ``` 在此示例中,我们首先创建了一个 `CredentialsProvider` 对象,该对象包含要用于身份验证用户名和密码。然后,我们使用 `HttpClients.custom()` 方法创建一个 `CloseableHttpClient` 实例,并将 `CredentialsProvider` 对象设置为默认凭据提供程序。最后,我们执行 HTTP GET 请求并处理响应实体。 请注意,我们需要指定要进行身份验证的范围(即主机名和端口号)。在本例中,我们将其设置为“localhost”和“8080”,但您应该将其替换为适当的值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智慧浩海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值