下面列出了怎么用org.apache.http.impl.client.BasicCredentialsProvider的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testUrlCred() throws HTTPException {
String url = "https://" + username + ":" + password + "@" + host + "/something/garbage.grb?query";
logger.info("Testing {}", url);
try (HTTPMethod method = HTTPFactory.Get(url)) {
HTTPSession session = method.getSession();
method.close();
session.setCredentialsProvider(new BasicCredentialsProvider());
try (HTTPMethod method2 = HTTPFactory.Get(session, url)) {
HTTPSession session2 = method2.getSession();
CredentialsProvider credentialsProvider = session2.sessionprovider;
assertThat(credentialsProvider).isNotNull();
AuthScope expectedAuthScope = new AuthScope(host, 80);
Credentials credentials = credentialsProvider.getCredentials(expectedAuthScope);
assertThat(credentials).isNotNull();
assertThat(credentials.getUserPrincipal().getName()).isEqualTo(username);
assertThat(credentials.getPassword()).isEqualTo(password);
}
}
}
public void init() {
RestClientBuilder restClientBuilder = RestClient.builder(parseHttpHost(esHosts)
.toArray(new HttpHost[0]));
if (this.settings != null && this.settings.size() > 0 &&
!Strings.isNullOrEmpty(this.settings.get("username"))
&& !Strings.isNullOrEmpty(this.settings.get("password"))) {
String userName = this.settings.get("username");
String password = this.settings.get("password");
final CredentialsProvider credentialsProvider =
new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(userName, password));
restClientBuilder.setHttpClientConfigCallback(httpAsyncClientBuilder -> {
httpAsyncClientBuilder.disableAuthCaching();
return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
});
}
restHighLevelClient = new RestHighLevelClient(restClientBuilder);
this.restLowLevelClient = restHighLevelClient.getLowLevelClient();
if (sniff) {
sniffer = Sniffer.builder(restLowLevelClient).setSniffIntervalMillis(5 * 60 * 1000).build();
}
}
/**
* Builds elastic rest client from user configuration
*
* @param coordinates list of {@code hostname/port} to connect to
* @return newly initialized low-level rest http client for ES
*/
private static RestClient connect(Map<String, Integer> coordinates,
Map<String, String> userConfig) {
Objects.requireNonNull(coordinates, "coordinates");
Preconditions.checkArgument(!coordinates.isEmpty(), "no ES coordinates specified");
final Set<HttpHost> set = new LinkedHashSet<>();
for (Map.Entry<String, Integer> entry : coordinates.entrySet()) {
set.add(new HttpHost(entry.getKey(), entry.getValue()));
}
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(userConfig.getOrDefault("esUser", "none"),
userConfig.getOrDefault("esPass", "none")));
return RestClient.builder(set.toArray(new HttpHost[0]))
.setHttpClientConfigCallback(httpClientBuilder ->
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))
.setMaxRetryTimeoutMillis(300000).build();
}
private void addCredentials( HttpClientContext context ) {
String host = environmentSubstitute( hostname );
int port = Const.toInt( environmentSubstitute( this.port ), 80 );
String userName = environmentSubstitute( username );
String password = Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( this.password ) );
String proxyHost = environmentSubstitute( proxyHostname );
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( userName, password );
if ( !Utils.isEmpty( proxyHost ) && host.equals( "localhost" ) ) {
host = "127.0.0.1";
}
provider.setCredentials( new AuthScope( host, port ), credentials );
context.setCredentialsProvider( provider );
// Generate BASIC scheme object and add it to the local auth cache
HttpHost target = new HttpHost( host, port, isSslMode() ? HTTPS : HTTP );
AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
authCache.put( target, basicAuth );
context.setAuthCache( authCache );
}
@Override public void setUsernamePassword(AuthenticationType authType, String username,
String password) {
this.credentials = new UsernamePasswordCredentials(
Objects.requireNonNull(username), Objects.requireNonNull(password));
this.credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, credentials);
RegistryBuilder<AuthSchemeProvider> authRegistryBuilder = RegistryBuilder.create();
switch (authType) {
case BASIC:
authRegistryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory());
break;
case DIGEST:
authRegistryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory());
break;
default:
throw new IllegalArgumentException("Unsupported authentiation type: " + authType);
}
this.authRegistry = authRegistryBuilder.build();
}
public static void main(String[] args) throws Exception {
HttpClientContextFactory ctxFact = new HttpClientContextFactory() {
public HttpClientContext create() {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope("localhost", 8080, AuthScope.ANY_REALM, "basic"),
new UsernamePasswordCredentials("user", "password"));
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
return context;
}
};
HttpEndpoint endpoint = new HttpEndpoint(new URI("http://localhost:8080/rpc/http"), ctxFact);
HttpResponse resp = endpoint.exec("rpc.http.version", null, null);
if (resp.isIsBinary()) {
System.out.println("binary");
System.out.println(resp.getInputStream().getName());
} else {
System.out.println(resp.getRpcResponse().getResult());
}
}
protected Maven2Client createMaven2Client(final URL repositoryUrl, final String username, final String password)
throws Exception
{
AuthScope scope = new AuthScope(repositoryUrl.getHost(), -1);
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(scope, new UsernamePasswordCredentials(username, password));
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
requestConfigBuilder.setExpectContinueEnabled(true);
HttpClientContext httpClientContext = HttpClientContext.create();
httpClientContext.setRequestConfig(requestConfigBuilder.build());
return new Maven2Client(
HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build(),
httpClientContext,
repositoryUrl.toURI()
);
}
/**
* Init method for this publisher.
*
* @param velocityRenderer
* the velocityRenderer to set
* @param httpClient
* http client
*/
protected void init(final VelocityEventRenderer velocityRenderer,
final HttpClient httpClient) {
this.velocityRenderer = velocityRenderer;
this.httpClient = httpClient;
if (getHttpAuthentication() != null) {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST,
AuthScope.ANY_PORT), new UsernamePasswordCredentials(
getHttpAuthentication().getUsername(),
getHttpAuthentication().getPassword()));
// Add AuthCache to the execution context
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
}
}
public boolean deleteArtifact(String longUrl) {
try {
CloseableHttpClient httpClient;
if (getUserName() != null && getPassword() != null) {
URL url = new URL(getUrl());
HttpHost httpHost = new HttpHost(url.getHost(), url.getPort());
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(httpHost),
new UsernamePasswordCredentials(getUserName(), getPassword()));
httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
} else {
httpClient = HttpClientBuilder.create().build();
}
RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
restTemplate.delete(new URI(longUrl));
} catch (Exception e) {
return false;
}
return true;
}
protected CloseableHttpResponse execute(final HttpUriRequest request, String username, String password)
throws IOException
{
log.debug("Authorizing request for {} using credentials provided for username: {}",
request.getURI(), username);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
HttpHost host = URIUtils.extractHost(request.getURI());
AuthCache authCache = new BasicAuthCache();
authCache.put(host, new BasicScheme());
HttpClientContext clientContext = new HttpClientContext(httpClientContext);
clientContext.setAuthCache(authCache);
clientContext.setCredentialsProvider(credsProvider);
return execute(request, clientContext);
}
@Test
public void verifySecurityInitializedExplicitUser() throws Exception {
webServer = new BrooklynWebServer(newManagementContext(brooklynProperties));
webServer.start();
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("myuser", "somepass"));
HttpClient client = HttpTool.httpClientBuilder()
.credentials(new UsernamePasswordCredentials("myuser", "somepass"))
.uri(webServer.getRootUrl())
.build();
try {
HttpToolResponse response = HttpTool.execAndConsume(client, new HttpGet(webServer.getRootUrl()));
assertEquals(response.getResponseCode(), 401);
} finally {
webServer.stop();
}
}
private HttpClientBuilder createHttpClientBuilder(boolean useKey) throws WxPayException {
HttpClientBuilder httpClientBuilder = HttpClients.custom();
if (useKey) {
this.initSSLContext(httpClientBuilder);
}
if (StringUtils.isNotBlank(this.getConfig().getHttpProxyHost())
&& this.getConfig().getHttpProxyPort() > 0) {
// 使用代理服务器 需要用户认证的代理服务器
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(
new AuthScope(this.getConfig().getHttpProxyHost(), this.getConfig().getHttpProxyPort()),
new UsernamePasswordCredentials(this.getConfig().getHttpProxyUsername(), this.getConfig().getHttpProxyPassword()));
httpClientBuilder.setDefaultCredentialsProvider(provider);
}
return httpClientBuilder;
}
@BeforeClass
public static void startElasticsearchContainerAndClient() throws IOException {
container = new ElasticsearchContainer(ELASTICSEARCH_CONTAINER_VERSION);
container.start();
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USER_NAME, PASSWORD));
RestClientBuilder builder = RestClient.builder(HttpHost.create(container.getHttpHostAddress()))
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
client = new RestHighLevelClient(builder);
client.indices().create(new CreateIndexRequest(INDEX), RequestOptions.DEFAULT);
reporter.reset();
}
public static CloseableHttpClient createHttpClient(int timeout, ProxyServerInfo proxyServerInfo) {
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig);
if (proxyServerInfo != null) {
HttpHost proxy = new HttpHost(proxyServerInfo.getHost(), proxyServerInfo.getPort(), proxyServerInfo.getProtocol());
httpClientBuilder = httpClientBuilder.setProxy(proxy);
if (proxyServerInfo.getPrincipal() != null && proxyServerInfo.getPassword() != null) {
Credentials credentials = new UsernamePasswordCredentials(proxyServerInfo.getPrincipal(), proxyServerInfo.getPassword());
AuthScope authScope = new AuthScope(proxyServerInfo.getHost(), proxyServerInfo.getPort());
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(authScope, credentials);
httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
}
return httpClientBuilder.build();
}
public static String convertMp3(final String mp3Path) throws URISyntaxException, IOException {
// get credentials for webservice from application config
final String apiKey = SkillConfig.getTranslatorConvertServiceUser();
final String apiPass = SkillConfig.getTranslatorConvertServicePass();
// build uri
final String bucketName = SkillConfig.getS3BucketName();
final URIBuilder uri = new URIBuilder(SkillConfig.getTranslatorConvertServiceUrl()).addParameter("bucket", bucketName).addParameter("path", mp3Path);
// set up web request
final HttpGet httpGet = new HttpGet(uri.build());
httpGet.setHeader("Content-Type", "text/plain");
// set up credentials
final CredentialsProvider provider = new BasicCredentialsProvider();
final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(apiKey, apiPass);
provider.setCredentials(AuthScope.ANY, credentials);
// send request to convert webservice
final HttpResponse response =
HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build().execute(httpGet);
//Validate.inclusiveBetween(200, 399, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
// work on response
final HttpEntity entity = response.getEntity();
return IOUtils.toString(entity.getContent(), "UTF-8");
}
@BeforeClass
public static void startElasticsearchContainerAndClient() throws IOException {
// Start the container
container = new ElasticsearchContainer(ELASTICSEARCH_CONTAINER_VERSION);
container.start();
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USER_NAME, PASSWORD));
RestClientBuilder builder = RestClient.builder(HttpHost.create(container.getHttpHostAddress()))
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
lowLevelClient = builder.build();
client = new RestHighLevelClient(lowLevelClient);
lowLevelClient.performRequest("PUT", "/" + INDEX);
reporter.reset();
}
public ElasticConnection(String host, int port, String user, String pwd,
int maxConnectionAttempts, long connectionRetryBackoff) {
logger.info("elastic auth enabled");
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(user, pwd));
//TODO add configuration for https also, and many nodes instead of only one
client = new RestHighLevelClient(
RestClient.builder(
new HttpHost(host, port)).setHttpClientConfigCallback(
httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
)
);
this.maxConnectionAttempts = maxConnectionAttempts;
this.connectionRetryBackoff = connectionRetryBackoff;
}
private void init(String host, int port, String userName, String password) {
this.host = host;
this.port = port;
this.userName = userName;
this.password = password;
this.baseUrl = SCHEME_HTTP + host + ":" + port + KYLIN_API_PATH;
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(httpParams, httpSocketTimeoutMs);
HttpConnectionParams.setConnectionTimeout(httpParams, httpConnectionTimeoutMs);
final PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
KylinConfig config = KylinConfig.getInstanceFromEnv();
cm.setDefaultMaxPerRoute(config.getRestClientDefaultMaxPerRoute());
cm.setMaxTotal(config.getRestClientMaxTotal());
client = new DefaultHttpClient(cm, httpParams);
if (userName != null && password != null) {
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
provider.setCredentials(AuthScope.ANY, credentials);
client.setCredentialsProvider(provider);
}
}
private void verify(String url, String user, String pass) {
try {
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, pass);
provider.setCredentials(AuthScope.ANY, credentials);
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
HttpResponse response = client.execute(new HttpGet(url));
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new ValidationException("verify elasticsearch node [" + url + "] failure, response status: " + response);
}
logger.info("Verify Es MediaSource successfully.");
} catch (Exception e) {
throw new ValidationException("verify elasticsearch node [" + url + "] failure, cause of: " + e);
}
}
private static void startRestClient() throws IOException {
if (client == null) {
RestClientBuilder builder = RestClient.builder(HttpHost.create(testCluster));
if (testClusterUser != null) {
final CredentialsProvider credentialsProvider =
new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(testClusterUser, testClusterPass));
builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
.setDefaultCredentialsProvider(credentialsProvider));
}
client = builder.build();
testClusterRunning();
}
}
protected CloseableHttpClient buildHttpClient() {
HttpClientBuilder httpClientBuilder = HttpClients.custom();
CredentialsProvider credsProvider = new BasicCredentialsProvider();
try {
Credentials credentials = check.getCredentials();
if (credentials != null) {
basicAuthentication(httpClientBuilder, credsProvider, credentials);
}
} catch (Exception ex) {
throw new RuntimeException("Could not use credentials");
}
// set proxy
if (check.getHttpProxyUsername() != null && !check.getHttpProxyPassword().isEmpty()) {
credsProvider.setCredentials(new AuthScope(check.getHttpProxyServer(), check.getHttpProxyPort()),
new UsernamePasswordCredentials(check.getHttpProxyUsername(), check.getHttpProxyPassword()));
httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
}
return httpClientBuilder.build();
}
@PostConstruct
public void init() {
try {
log.trace("Adding elastic rest endpoint... host [{}], port [{}], scheme name [{}]",
host, port, schemeName);
RestClientBuilder builder = RestClient.builder(
new HttpHost(host, port, schemeName));
if (StringUtils.isNotEmpty(userName) &&
StringUtils.isNotEmpty(password)) {
log.trace("...using username [{}] and password ***", userName);
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(userName, password));
builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
}
this.restClient = builder.build();
} catch (Exception e) {
log.error("Sink init failed!", e);
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* 默认是 Bsic认证机制
*
* @param ip
* @param username
* @param password
* @return
*/
public static HttpClient getHtpClient(String ip, int port, String username, String password) {
HttpHost proxy = new HttpHost(ip, port);
Lookup<AuthSchemeProvider> authProviders =
RegistryBuilder.<AuthSchemeProvider>create()
.register(AuthSchemes.BASIC, new BasicSchemeFactory())
.build();
BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
if (username != null && password != null) {
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
} else {
credsProvider.setCredentials(AuthScope.ANY, null);
}
RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
CloseableHttpClient httpClient = HttpClients
.custom()
.setConnectionManager(cm)
.setProxy(proxy)
.setRedirectStrategy(new LaxRedirectStrategy())
.setDefaultRequestConfig(requestConfig)
.setDefaultAuthSchemeRegistry(authProviders)
.setDefaultCredentialsProvider(credsProvider)
.build();
return httpClient;
}
private HttpClientContext prepareContext()
{
HttpHost targetHost = new HttpHost(serverConfig.getServerName(), serverConfig.getPort(), serverConfig.isUseHTTPS() ? "https" : "http");
AuthCache authCache = new BasicAuthCache();
authCache.put(targetHost, new BasicScheme());
CredentialsProvider credsProvider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials
= new UsernamePasswordCredentials(serverConfig.getUserName(), serverConfig.getPassword());
credsProvider.setCredentials(AuthScope.ANY, credentials);
// Add AuthCache to the execution context
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
return context;
}
public CMODataAbapClient(String endpoint, String user, String password) throws URISyntaxException {
this.endpoint = new URI(endpoint);
this.requestBuilder = new TransportRequestBuilder(this.endpoint);
// the same instance needs to be used as long as we are in the same session. Hence multiple
// clients must share the same cookie store. Reason: we are logged on with the first request
// and get a cookie. That cookie - expressing the user has already been logged in - needs to be
// present in all subsequent requests.
CookieStore sessionCookieStore = new BasicCookieStore();
BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
basicCredentialsProvider.setCredentials(
new AuthScope(this.endpoint.getHost(), this.endpoint.getPort()),
new UsernamePasswordCredentials(user, password));
this.clientFactory = new HttpClientFactory(sessionCookieStore, basicCredentialsProvider);
}
private CredentialsProvider getCredentialsProvider() {
Project project = getProject();
HelmExtension extension = project.getExtensions().getByType(HelmExtension.class);
String helmUser = extension.getCredentials().getUser();
String helmPass = extension.getCredentials().getPass();
if (helmUser == null) {
throw new IllegalArgumentException("deployment.helmUser not specified");
}
if (helmPass == null) {
throw new IllegalArgumentException("deployment.helmPass not specified");
}
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(helmUser, helmPass);
provider.setCredentials(AuthScope.ANY, credentials);
return provider;
}
protected CloseableHttpClient constructHttpClient() throws IOException {
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(20 * 1000)
.setConnectionRequestTimeout(20 * 1000)
.setSocketTimeout(20 * 1000)
.setMaxRedirects(20)
.build();
URL mmsc = new URL(apn.getMmsc());
CredentialsProvider credsProvider = new BasicCredentialsProvider();
if (apn.hasAuthentication()) {
credsProvider.setCredentials(new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
}
return HttpClients.custom()
.setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
.setRedirectStrategy(new LaxRedirectStrategy())
.setUserAgent(SilencePreferences.getMmsUserAgent(context, USER_AGENT))
.setConnectionManager(new BasicHttpClientConnectionManager())
.setDefaultRequestConfig(config)
.setDefaultCredentialsProvider(credsProvider)
.build();
}
protected CloseableHttpResponse execute(final HttpUriRequest request, String username, String password)
throws IOException
{
log.debug("Authorizing request for {} using credentials provided for username: {}",
request.getURI(), username);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
HttpHost host = URIUtils.extractHost(request.getURI());
AuthCache authCache = new BasicAuthCache();
authCache.put(host, new BasicScheme());
HttpClientContext clientContext = new HttpClientContext(httpClientContext);
clientContext.setAuthCache(authCache);
clientContext.setCredentialsProvider(credsProvider);
return execute(request, clientContext);
}
public static CloseableHttpClient createClient(String username, String password) {
HttpClientBuilder builder = HttpClientBuilder.create();
if (username != null && password != null) {
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY, new UsernamePasswordCredentials(username, password));
builder.setDefaultCredentialsProvider(credentialsProvider);
}
return builder.build();
}
private CredentialsProvider getCredentialsProvider() {
if (StringUtils.isEmpty(elasticSearchConfig.getUsername())
|| StringUtils.isEmpty(elasticSearchConfig.getPassword())) {
return null;
}
credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(elasticSearchConfig.getUsername(),
elasticSearchConfig.getPassword()));
return credentialsProvider;
}