基本身份验证
编辑基本身份验证编辑
可以通过在构建 RestClient
时通过其构建器提供 HttpClientConfigCallback
来配置基本身份验证。该接口有一个方法,该方法接收 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); } });