基本认证

构建RestClient时配置HttpClientConfigCallback来配置基本认证。 该接口有一个方法接收org.apache.http.impl.nio.client.HttpAsyncClientBuilder的一个实例作为参数,并具有相同的返回类型。 httpClientBuilder 被修改,然后返回。 在以下示例中,设置了基本身份验证。

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

Preemptive 身份验证可以禁用,这意味着每个发送出去的请求没有授权头,当收到HTTP 401响应时,将重新发送与基本身份验证头完全相同的请求。 可以通过HttpAsyncClientBuilder来禁用:

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