加载中

基本认证

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

var creds = Base64.getEncoder()
    .encodeToString("user:test-user-password".getBytes());

Rest5ClientBuilder restClient = Rest5Client
    .builder(new HttpHost("https", "localhost", 9200))
    .setDefaultHeaders(new Header[]{
        new BasicHeader("Authorization", "Basic " + creds)
    });

可以禁用抢占式认证 (Preemptive Authentication),这意味着每个请求都将发送而不带授权头部,以查看是否被接受,并在收到 HTTP 401 响应时,会以相同的基本认证头部重新发送完全相同的请求。如果您希望这样做,可以通过 HttpAsyncClientBuilder 禁用它。

HttpHost host = new HttpHost("http", "localhost", 9200);

var creds = Base64.getEncoder().encodeToString("user:test-user-password".getBytes());

CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
    .disableAuthCaching()
    .build();

Rest5ClientBuilder restClient = Rest5Client
    .builder(new HttpHost("https", "localhost", 9200))
    .setHttpClient(httpclient)
    .setDefaultHeaders(new Header[]{
        new BasicHeader("Authorization", "Basic " + creds)
    });
  1. 禁用抢占式认证
© . All rights reserved.