基本身份验证
编辑基本身份验证
编辑配置基本身份验证可以通过在构建 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); } });