HttpClientBuilder basic auth
2022-09-02 02:20:56
从HttpClient 4.3开始,我一直在使用HttpClientBuilder。我正在连接到具有基本身份验证的 REST 服务。我按如下方式设置凭据:
HttpClientBuilder builder = HttpClientBuilder.create();
// Get the client credentials
String username = Config.get(Constants.CONFIG_USERNAME);
String password = Config.get(Constants.CONFIG_PASSWORD);
// If username and password was found, inject the credentials
if (username != null && password != null)
{
CredentialsProvider provider = new BasicCredentialsProvider();
// Create the authentication scope
AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
// Create credential pair
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
// Inject the credentials
provider.setCredentials(scope, credentials);
// Set the default credentials provider
builder.setDefaultCredentialsProvider(provider);
}
但是,这不起作用(我正在使用的 REST 服务返回 401)。哪里出错了?