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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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。

1
2
3
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));