httpclient之basic认证

本文主要说明如何使用httpclient进行basic认证。

我们常用的登录是form形式,但也有的登录采用的basic认证,比如activeMq默认就是basic认证。

private final static CloseableHttpClient getBasicHttpClient(String username,String password) {
    // 创建HttpClientBuilder
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    // 设置BasicAuth
    CredentialsProvider provider = new BasicCredentialsProvider();
    // Create the authentication scope
    AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
    // Create credential pair,在此处填写用户名和密码
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username,password);
    // Inject the credentials
    provider.setCredentials(scope, credentials);
    // Set the default credentials provider
    httpClientBuilder.setDefaultCredentialsProvider(provider);
    // HttpClient
    CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
    return closeableHttpClient;
}

Ok,获取到CloseableHttpClient后,其他的操作就简单了。
比如想通过httpclient访问ActiveMQ的首页的内容,http://192.168.74.135:8161/admin

HttpGet get = new HttpGet("http://192.168.74.135:8161/admin");
CloseableHttpResponse response = getBasicHttpClient("admin","admin").execute(get);
System.out.println(EntityUtils.toString(response.getEntity));
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值