官方文档地址:Basic authentication
可以通过提供HttpClientConfigCallback
来配置基本身份验证,同时通过其构建器构建RestClient
。该接口有一个方法,该方法接收org.apache.http.impl.nio.client.HttpAsyncClientBuilder
的实例作为参数,并具有相同的返回类型。可以修改并返回 http 客户端构建器。在下面的示例中,我们设置了一个需要基本身份验证的默认凭据提供程序。
final CredentialsProvider credentialsProvider =
new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("user", "test-user-password"));
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200))
.setHttpClientConfigCallback(new HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder
.setDefaultCredentialsProvider(credentialsProvider);
}
});
可以禁用抢占式身份验证,这意味着每个请求都将在没有授权头的情况下发送,以查看是否被接受,并且在收到 HTTP 401 响应时,它将重新发送与基本身份验证头完全相同的请求。如果你想这样做,那么你可以通过HttpAsyncClientBuilder
来禁用它:
final CredentialsProvider credentialsProvider =
new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("user", "test-user-password"));
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200))
.setHttpClientConfigCallback(new HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
//禁用抢占式身份验证
httpClientBuilder.disableAuthCaching();
return httpClientBuilder
.setDefaultCredentialsProvider(credentialsProvider);
}
});