下面列出了org.apache.http.impl.client.HttpClientBuilder#setDefaultAuthSchemeRegistry() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected final CloseableHttpClient getHttpClient(final boolean useSpnego) throws Exception {
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
final HttpClientBuilder hcb = HttpClients.custom();
if (useSpnego) {
//SPNEGO/Kerberos setup
log.debug("SPNEGO activated");
final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true);// new NegotiateSchemeProvider();
final Credentials jaasCreds = new JaasCredentials();
credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds);
credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM), new NTCredentials("Guest", "Guest", "Guest",
"Guest"));
final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
.register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build();
hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry);
}
hcb.setDefaultCredentialsProvider(credsProvider);
hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(10 * 1000).build());
final CloseableHttpClient httpClient = hcb.build();
return httpClient;
}
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);
}
}
/**
* 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);
}
}
}
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 HttpClient buildSpengoHttpClient() {
HttpClientBuilder builder = HttpClientBuilder.create();
Lookup<AuthSchemeProvider> authSchemeRegistry
= RegistryBuilder.<AuthSchemeProvider>create().register(
AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() {
@Override
public Principal getUserPrincipal() {
return null;
}
@Override
public String getPassword() {
return null;
}
});
builder.setDefaultCredentialsProvider(credentialsProvider);
// Avoid output WARN: Cookie rejected
RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES)
.build();
builder.setDefaultRequestConfig(globalConfig);
CloseableHttpClient httpClient = builder.build();
return httpClient;
}
private HttpClient openConnection() throws IOException {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
if (sslContextService != null) {
try {
SSLContext sslContext = getSslSocketFactory(sslContextService);
httpClientBuilder.setSSLContext(sslContext);
} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | UnrecoverableKeyException | KeyManagementException e) {
throw new IOException(e);
}
}
if (credentialsService != null) {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(null, -1, null),
new KerberosKeytabCredentials(credentialsService.getPrincipal(), credentialsService.getKeytab()));
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
.register(AuthSchemes.SPNEGO, new KerberosKeytabSPNegoAuthSchemeProvider()).build();
httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
}
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
requestConfigBuilder.setConnectTimeout(connectTimeout);
requestConfigBuilder.setConnectionRequestTimeout(connectTimeout);
requestConfigBuilder.setSocketTimeout(connectTimeout);
httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
return httpClientBuilder.build();
}
/**
* @param proxy Proxy configuration
* @param listener Log listener
* @param prompt Prompt for proxy credentials
* @return Builder for HTTP client
*/
public HttpClientBuilder build(final Proxy proxy, final TranscriptListener listener, final LoginCallback prompt) {
final HttpClientBuilder configuration = HttpClients.custom();
// Use HTTP Connect proxy implementation provided here instead of
// relying on internal proxy support in socket factory
switch(proxy.getType()) {
case HTTP:
case HTTPS:
final HttpHost h = new HttpHost(proxy.getHostname(), proxy.getPort(), Scheme.http.name());
if(log.isInfoEnabled()) {
log.info(String.format("Setup proxy %s", h));
}
configuration.setProxy(h);
configuration.setProxyAuthenticationStrategy(new CallbackProxyAuthenticationStrategy(ProxyCredentialsStoreFactory.get(), host, prompt));
break;
}
configuration.setUserAgent(new PreferencesUseragentProvider().get());
final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000;
configuration.setDefaultSocketConfig(SocketConfig.custom()
.setTcpNoDelay(true)
.setSoTimeout(timeout)
.build());
configuration.setDefaultRequestConfig(this.createRequestConfig(timeout));
configuration.setDefaultConnectionConfig(ConnectionConfig.custom()
.setBufferSize(preferences.getInteger("http.socket.buffer"))
.setCharset(Charset.forName(host.getEncoding()))
.build());
if(preferences.getBoolean("http.connections.reuse")) {
configuration.setConnectionReuseStrategy(new DefaultClientConnectionReuseStrategy());
}
else {
configuration.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
}
configuration.setRetryHandler(new ExtendedHttpRequestRetryHandler(preferences.getInteger("http.connections.retry")));
configuration.setServiceUnavailableRetryStrategy(new DisabledServiceUnavailableRetryStrategy());
if(!preferences.getBoolean("http.compression.enable")) {
configuration.disableContentCompression();
}
configuration.setRequestExecutor(new LoggingHttpRequestExecutor(listener));
// Always register HTTP for possible use with proxy. Contains a number of protocol properties such as the
// default port and the socket factory to be used to create the java.net.Socket instances for the given protocol
configuration.setConnectionManager(this.createConnectionManager(this.createRegistry()));
configuration.setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create()
.register(AuthSchemes.BASIC, new BasicSchemeFactory(
Charset.forName(preferences.getProperty("http.credentials.charset"))))
.register(AuthSchemes.DIGEST, new DigestSchemeFactory(
Charset.forName(preferences.getProperty("http.credentials.charset"))))
.register(AuthSchemes.NTLM, preferences.getBoolean("webdav.ntlm.windows.authentication.enable") && WinHttpClients.isWinAuthAvailable() ?
new BackportWindowsNTLMSchemeFactory(null) :
new NTLMSchemeFactory())
.register(AuthSchemes.SPNEGO, preferences.getBoolean("webdav.ntlm.windows.authentication.enable") && WinHttpClients.isWinAuthAvailable() ?
new BackportWindowsNegotiateSchemeFactory(null) :
new SPNegoSchemeFactory())
.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build());
return configuration;
}