官方文档地址:Basic authentication


    可以通过提供HttpClientConfigCallback来配置基本身份验证,同时通过其构建器构建RestClient。该接口有一个方法,该方法接收org.apache.http.impl.nio.client.HttpAsyncClientBuilder的实例作为参数,并具有相同的返回类型。可以修改并返回 http 客户端构建器。在下面的示例中,我们设置了一个需要基本身份验证的默认凭据提供程序。

    1. final CredentialsProvider credentialsProvider =
    2. new BasicCredentialsProvider();
    3. credentialsProvider.setCredentials(AuthScope.ANY,
    4. new UsernamePasswordCredentials("user", "test-user-password"));
    5. RestClientBuilder builder = RestClient.builder(
    6. new HttpHost("localhost", 9200))
    7. .setHttpClientConfigCallback(new HttpClientConfigCallback() {
    8. @Override
    9. public HttpAsyncClientBuilder customizeHttpClient(
    10. HttpAsyncClientBuilder httpClientBuilder) {
    11. return httpClientBuilder
    12. .setDefaultCredentialsProvider(credentialsProvider);
    13. }
    14. });

    可以禁用抢占式身份验证,这意味着每个请求都将在没有授权头的情况下发送,以查看是否被接受,并且在收到 HTTP 401 响应时,它将重新发送与基本身份验证头完全相同的请求。如果你想这样做,那么你可以通过HttpAsyncClientBuilder来禁用它:

    1. final CredentialsProvider credentialsProvider =
    2. new BasicCredentialsProvider();
    3. credentialsProvider.setCredentials(AuthScope.ANY,
    4. new UsernamePasswordCredentials("user", "test-user-password"));
    5. RestClientBuilder builder = RestClient.builder(
    6. new HttpHost("localhost", 9200))
    7. .setHttpClientConfigCallback(new HttpClientConfigCallback() {
    8. @Override
    9. public HttpAsyncClientBuilder customizeHttpClient(
    10. HttpAsyncClientBuilder httpClientBuilder) {
    11. //禁用抢占式身份验证
    12. httpClientBuilder.disableAuthCaching();
    13. return httpClientBuilder
    14. .setDefaultCredentialsProvider(credentialsProvider);
    15. }
    16. });