下面列出了org.apache.http.impl.client.HttpClientBuilder#setDefaultCredentialsProvider() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public CloseableHttpClient build() {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setConnectionManager( manager );
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
if ( socketTimeout > 0 ) {
requestConfigBuilder.setSocketTimeout( socketTimeout );
}
if ( connectionTimeout > 0 ) {
requestConfigBuilder.setConnectTimeout( socketTimeout );
}
if ( proxy != null ) {
requestConfigBuilder.setProxy( proxy );
}
httpClientBuilder.setDefaultRequestConfig( requestConfigBuilder.build() );
if ( provider != null ) {
httpClientBuilder.setDefaultCredentialsProvider( provider );
}
if ( redirectStrategy != null ) {
httpClientBuilder.setRedirectStrategy( redirectStrategy );
}
return httpClientBuilder.build();
}
protected HttpClientBuilder setupProxy(HttpClientBuilder clientBuilder) {
if (this.proxy == null) {
return clientBuilder;
}
if (proxy.getUsername() != null && !proxy.getUsername().isEmpty() &&
proxy.getPassword() != null && !proxy.getPassword().isEmpty()) {
clientBuilder.setProxyAuthenticationStrategy(ProxyAuthenticationStrategy.INSTANCE);
BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
AuthScope proxyAuthScope = new AuthScope(proxy.getHost(), proxy.getPort());
UsernamePasswordCredentials proxyAuthentication =
new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword());
basicCredentialsProvider.setCredentials(proxyAuthScope, proxyAuthentication);
clientBuilder.setDefaultCredentialsProvider(basicCredentialsProvider);
}
return clientBuilder;
}
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;
}
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();
}
private CloseableHttpClient getHttpClient(String url) {
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout)
.setConnectTimeout(connectionTimeout)
.build();
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setDefaultRequestConfig(requestConfig);
httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager());
httpClientBuilder.setUserAgent(ASQATASUN_USER_AGENT);
if (isProxySet(url)) {
LOGGER.debug(("Set proxy with " + proxyHost + " and " + proxyPort));
httpClientBuilder.setProxy(new HttpHost(proxyHost, Integer.valueOf(proxyPort)));
if (isProxyCredentialSet()) {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(proxyHost, Integer.valueOf(proxyPort)),
new UsernamePasswordCredentials(proxyUser, proxyPassword));
httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
LOGGER.debug(("Set proxy credentials " + proxyHost + " and " + proxyPort + " and " + proxyUser + " and " + proxyPassword));
}
}
return httpClientBuilder.build();
}
public void setCredentialsProvider(RfRequestDTO requestDTO, HttpClientBuilder clientBuilder) {
DigestAuthDTO digestAuthDTO = requestDTO.getDigestAuthDTO();
if (digestAuthDTO == null) {
return;
}
String userName = digestAuthDTO.getUsername();
String password = digestAuthDTO.getPassword();
if (userName == null || userName.isEmpty() || password == null || password.isEmpty()) {
return;
}
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
new UsernamePasswordCredentials(userName, password));
clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
/**
* Add a proxy to the http request if it has been set within settings
*
* @param builder
* Builder used to create the http client
* @param settings
* Settings which contain any proxy configuration details
*/
public static void addProxyConfig(HttpClientBuilder builder,
HttpClientSettings settings) {
if (settings.isProxyEnabled()) {
log.info("Configuring Proxy. Proxy Host: " + settings.getProxyHost() + " " +
"Proxy Port: " + settings.getProxyPort());
builder.setRoutePlanner(new SdkProxyRoutePlanner(
settings.getProxyHost(), settings.getProxyPort(), settings.getNonProxyHosts()));
if (settings.isAuthenticatedProxy()) {
builder.setDefaultCredentialsProvider(ApacheUtils.newProxyCredentialsProvider(settings));
}
}
}
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();
}
public CloseableHttpClient build() {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setConnectionManager( manager );
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
if ( socketTimeout > 0 ) {
requestConfigBuilder.setSocketTimeout( socketTimeout );
}
if ( connectionTimeout > 0 ) {
requestConfigBuilder.setConnectTimeout( socketTimeout );
}
if ( proxy != null ) {
requestConfigBuilder.setProxy( proxy );
}
if ( cookieSpec != null ) {
requestConfigBuilder.setCookieSpec( cookieSpec );
}
if ( maxRedirects > 0 ) {
requestConfigBuilder.setMaxRedirects( maxRedirects );
}
if ( allowCircularRedirects ) {
requestConfigBuilder.setCircularRedirectsAllowed( true );
}
if ( !rejectRelativeRedirect ) {
requestConfigBuilder.setRelativeRedirectsAllowed( true );
}
// RequestConfig built
httpClientBuilder.setDefaultRequestConfig( requestConfigBuilder.build() );
if ( provider != null ) {
httpClientBuilder.setDefaultCredentialsProvider( provider );
}
if ( redirectStrategy != null ) {
httpClientBuilder.setRedirectStrategy( redirectStrategy );
}
return httpClientBuilder.build();
}
private static HttpClientBuilder provideHttpBuilder(final InfluxDBSettings settings) {
final HttpClientBuilder builder = HttpClientBuilder.create();
if (isNoneBlank(settings.userName, settings.userPassword)) {
final CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(
AuthScope.ANY, new UsernamePasswordCredentials(settings.userName, settings.userPassword));
builder.setDefaultCredentialsProvider(provider);
}
return builder;
}
private CloseableHttpClient authenticate(HttpClientBuilder clientBuilder, HttpRequestBase requestBase, HttpContext httpContext) {
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(
new AuthScope(requestBase.getURI().getHost(), requestBase.getURI().getPort()),
CredentialsUtil.readCredentials(credentials, vaultConfiguration));
clientBuilder.setDefaultCredentialsProvider(provider);
AuthCache authCache = new BasicAuthCache();
authCache.put(URIUtils.extractHost(requestBase.getURI()), new BasicScheme());
httpContext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
return clientBuilder.build();
}
public WebServicesClient(ClientConfig config)
{
if (SecurityUtils.isHadoopWebSecurityEnabled()) {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setConnectionManager(connectionManager);
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
httpClientBuilder.setDefaultAuthSchemeRegistry(authRegistry);
ApacheHttpClient4Handler httpClientHandler = new ApacheHttpClient4Handler(httpClientBuilder.build(), new BasicCookieStore(), false);
client = new Client(httpClientHandler, config);
} else {
client = Client.create(config);
}
}
private static void configureProxy(HttpClientBuilder builder, String url) {
List<Proxy> proxies = ProxySelector.getDefault().select(URI.create(url));
if (!proxies.isEmpty()) {
Optional<Proxy> proxy = proxies.stream().filter(p -> p.type().equals(Proxy.Type.HTTP))
.findFirst();
if (proxy.isPresent()) {
InetSocketAddress address = (InetSocketAddress) proxy.get().address();
builder.setProxy(new HttpHost(address.getHostName(), address.getPort()));
try {
PasswordAuthentication auth = Authenticator.requestPasswordAuthentication(
address.getHostName(), null, address.getPort(),
(url.startsWith("https://") ? "https" : "http"),
"Credentials for proxy " + proxy, null, new URL(url),
Authenticator.RequestorType.PROXY);
if (auth != null) {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(address.getHostName(), address.getPort()),
new UsernamePasswordCredentials(auth.getUserName(),
String.valueOf(auth.getPassword())));
builder.setDefaultCredentialsProvider(credsProvider);
}
}
catch (MalformedURLException e) {
}
}
}
}
public ClientHttpRequestFactory createRequestFactory(HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) {
HttpClientBuilder httpClientBuilder = HttpClients.custom()
.useSystemProperties();
if (trustSelfSignedCerts) {
httpClientBuilder.setSslcontext(buildSslContext());
httpClientBuilder.setHostnameVerifier(BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
}
if (httpProxyConfiguration != null) {
HttpHost proxy = new HttpHost(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort());
httpClientBuilder.setProxy(proxy);
if (httpProxyConfiguration.isAuthRequired()) {
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(httpProxyConfiguration.getProxyHost(),
httpProxyConfiguration.getProxyPort()),
new UsernamePasswordCredentials(httpProxyConfiguration.getUsername(),
httpProxyConfiguration.getPassword()));
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
httpClientBuilder.setRoutePlanner(routePlanner);
}
HttpClient httpClient = httpClientBuilder.build();
return new HttpComponentsClientHttpRequestFactory(httpClient);
}
/**
* Set up authentication for HTTP Basic/HTTP Digest/SPNEGO.
*
* @param httpClientBuilder The client builder
* @return The context
* @throws HttpException
*/
private void setupAuthentication( HttpClientBuilder httpClientBuilder ) throws HttpException {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(username, password));
httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
if (authType == AuthType.always) {
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
HttpHost target = new HttpHost(host, port, isOverSsl
? "https"
: "http");
authCache.put(target, basicAuth);
// Add AuthCache to the execution context
httpContext.setAuthCache(authCache);
} else {
if (!StringUtils.isNullOrEmpty(kerberosServicePrincipalName)) {
GssClient gssClient = new GssClient(username, password, kerberosClientKeytab, krb5ConfFile);
AuthSchemeProvider nsf = new SPNegoSchemeFactory(gssClient, kerberosServicePrincipalName,
kerberosServicePrincipalType);
final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
.register(AuthSchemes.SPNEGO,
nsf)
.build();
httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
}
}
}
private HttpClientBuilder getHttpClient(HttpContext httpContext) {
HttpClientBuilder client = HttpClients.custom();
client.useSystemProperties(); // see also: com.intellij.util.net.ssl.CertificateManager
// we need to get redirected result after login (which is done with POST) for extracting xGerritAuth
client.setRedirectStrategy(new LaxRedirectStrategy());
httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
RequestConfig.Builder requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECTION_TIMEOUT_MS) // how long it takes to connect to remote host
.setSocketTimeout(CONNECTION_TIMEOUT_MS) // how long it takes to retrieve data from remote host
.setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS);
client.setDefaultRequestConfig(requestConfig.build());
CredentialsProvider credentialsProvider = getCredentialsProvider();
client.setDefaultCredentialsProvider(credentialsProvider);
if (authData.isLoginAndPasswordAvailable()) {
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(authData.getLogin(), authData.getPassword()));
BasicScheme basicAuth = new BasicScheme();
httpContext.setAttribute(PREEMPTIVE_AUTH, basicAuth);
client.addInterceptorFirst(new PreemptiveAuthHttpRequestInterceptor(authData));
}
client.addInterceptorLast(new UserAgentHttpRequestInterceptor());
for (HttpClientBuilderExtension httpClientBuilderExtension : httpClientBuilderExtensions) {
client = httpClientBuilderExtension.extend(client, authData);
credentialsProvider = httpClientBuilderExtension.extendCredentialProvider(client, credentialsProvider, authData);
}
return client;
}
protected void setAuthentication(Map<String, Object> parameters, HttpClientBuilder clientBuilder)
{
String username = getUsername(parameters);
if (username != null)
{
String password = getPassword(parameters);
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//FIXME proxy authentication?
credentialsProvider.setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(username, password));
clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
}
private Response getUrlContents(String theUrl, boolean useAuth, boolean followRedirects) {
StringBuilder content = new StringBuilder();
int code;
try {
HttpClientBuilder builder = HttpClientBuilder.create();
if (!followRedirects) {
builder.disableRedirectHandling();
}
if (useAuth) {
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "password");
provider.setCredentials(AuthScope.ANY, credentials);
builder.setDefaultCredentialsProvider(provider);
}
HttpClient client = builder.build();
HttpResponse response = client.execute(new HttpGet(theUrl));
code = response.getStatusLine().getStatusCode();
if (response.getEntity() != null) {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return new Response(code, content.toString());
}
private void basicAuthentication(HttpClientBuilder httpClientBuilder, CredentialsProvider credsProvider, Credentials credentials) throws URISyntaxException {
URI uri = new URI(check.getUrl());
credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(credentials.getUsername(), credentials.getPassword()));
httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
}
public static CloseableHttpClient acceptsUntrustedCertsHttpClient(boolean withProxy, ProxyHostInfo hostInfo, int connectionTimeout, int connectionRequestTimeout, int socketTimeout)
throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
HttpClientBuilder b = HttpClientBuilder.create();
/**
* set http proxy
*/
b.setDefaultRequestConfig(
RequestConfig.custom().setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout).build()
);
if(withProxy){
HttpHost proxy=new HttpHost(hostInfo.getHostName(),hostInfo.getPort());
b.setProxy(proxy);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(proxy.getHostName(), proxy.getPort()),
new UsernamePasswordCredentials(hostInfo.getUserName(), hostInfo.getPassword()));
b.setDefaultCredentialsProvider(credsProvider);
}
SSLContext sslContext = new SSLContextBuilder().useProtocol("TLSv1.2").loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
b.setSSLContext(sslContext);
b.setConnectionTimeToLive(180, TimeUnit.SECONDS);
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory)
.build();
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connMgr.setMaxTotal(200);
connMgr.setDefaultMaxPerRoute(100);
b.setConnectionManager(connMgr);
CloseableHttpClient client = b.build();
return client;
}