下面列出了org.apache.http.impl.client.HttpClientBuilder#setSSLSocketFactory() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected void init() throws GerbilException {
HttpClientBuilder builder = HttpManagement.getInstance().generateHttpClientBuilder();
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream instream = this.getClass().getClassLoader().getResourceAsStream(KEY_STORE_RESOURCE_NAME);
try {
keyStore.load(instream, KEY_STORE_PASSWORD);
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, new TrustSelfSignedStrategy())
.build();
builder.setSSLContext(sslcontext);
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
builder.setSSLSocketFactory(sslsf);
CloseableHttpClient localClient = builder.build();
this.setClient(localClient);
} catch (Exception e) {
throw new GerbilException("Couldn't initialize SSL context.", e, ErrorTypes.ANNOTATOR_LOADING_ERROR);
}
this.setClient(builder.build());
}
/**
* It creates an {@link CloseableHttpClient} object.
* If {@link #validateServerHttpsCertificate} indicates that we should not validate HTTPS server certificate, we use an insecure SSL factory; the insecure factory is created using {@link #createInsecureSslFactory()}.
*/
protected CloseableHttpClient createHttpClient() {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(createRequestConfig());
if (!validateServerHttpsCertificate) {
SSLConnectionSocketFactory sslsf = createInsecureSslFactory();
httpClientBuilder.setSSLSocketFactory(sslsf);
}
return httpClientBuilder.build();
}
@Override
public final HttpClientBuilder apply(final HttpClientBuilder builder) {
final SSLContext context;
try {
final SSLContextBuilder ssl = SSLContexts.custom();
ssl.loadTrustMaterial((chain, type) -> true);
context = ssl.build();
//@checkstyle IllegalCatchCheck (1 lines)
} catch (final Exception exp) {
throw new IllegalStateException(exp);
}
return builder.setSSLSocketFactory(
new SSLConnectionSocketFactory(context, (ctx, session) -> true)
);
}
public void setWxMpConfigStorage(WxMpConfigStorage wxConfigProvider) {
this.wxMpConfigStorage = wxConfigProvider;
String http_proxy_host = wxMpConfigStorage.getHttp_proxy_host();
int http_proxy_port = wxMpConfigStorage.getHttp_proxy_port();
String http_proxy_username = wxMpConfigStorage.getHttp_proxy_username();
String http_proxy_password = wxMpConfigStorage.getHttp_proxy_password();
final HttpClientBuilder builder = HttpClients.custom();
if (StringUtils.isNotBlank(http_proxy_host)) {
// 使用代理服务器
if (StringUtils.isNotBlank(http_proxy_username)) {
// 需要用户认证的代理服务器
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(http_proxy_host, http_proxy_port),
new UsernamePasswordCredentials(http_proxy_username, http_proxy_password));
builder
.setDefaultCredentialsProvider(credsProvider);
} else {
// 无需用户认证的代理服务器
}
httpProxy = new HttpHost(http_proxy_host, http_proxy_port);
}
if (wxConfigProvider.getSSLContext() != null){
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
wxConfigProvider.getSSLContext(),
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
builder.setSSLSocketFactory(sslsf);
}
httpClient = builder.build();
}
private void initSSLContext(HttpClientBuilder httpClientBuilder) throws WxPayException {
SSLContext sslContext = this.getConfig().getSslContext();
if (null == sslContext) {
sslContext = this.getConfig().initSSLContext();
}
SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
new String[]{"TLSv1"}, null, new DefaultHostnameVerifier());
httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
}
protected HttpClientBuilder clientBuilder(final URL nexusUrl, final boolean useCredentials) throws Exception {
HttpClientBuilder builder = HttpClients.custom();
builder.setDefaultRequestConfig(requestConfig());
if (useCredentials) {
doUseCredentials(nexusUrl, builder);
}
builder.setSSLSocketFactory(sslSocketFactory());
return builder;
}
/**
* Creates a new HTTP client.
*
* @param trustSelfSignedCertificate specifies whether to trust a self-signed certificate
* @param disableHostnameVerification specifies whether to turn off hostname verification
*
* @return the HTTP client
* @throws KeyStoreException if a key store exception occurs
* @throws NoSuchAlgorithmException if a no such algorithm exception occurs
* @throws KeyManagementException if key management exception
*/
public CloseableHttpClient createHttpClient(Boolean trustSelfSignedCertificate, Boolean disableHostnameVerification)
throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException
{
// Create an HTTP client builder.
HttpClientBuilder httpClientBuilder = HttpClients.custom();
// Create an SSL context builder.
SSLContextBuilder sslContextBuilder = SSLContexts.custom();
// If specified, setup a trust strategy that allows all certificates.
if (BooleanUtils.isTrue(trustSelfSignedCertificate))
{
sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
}
// If specified, turn hostname verification off.
HostnameVerifier hostnameVerifier = BooleanUtils.isTrue(disableHostnameVerification) ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER :
SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;
// Create and assign an SSL connection socket factory.
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);
// Build and return an HTTP client.
return httpClientBuilder.build();
}
public static String post(String url, String payload) throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(url);
// httpPost.addHeader("Cookie", "rememberMe=" + Base64.getEncoder().encodeToString(data));
HttpEntity httpEntity = new StringEntity(payload, "application/x-www-form-urlencoded", "utf-8");
httpPost.setEntity(httpEntity);
try {
HttpClientBuilder httpClientBuilder = HttpClients
.custom()
// .setProxy(new HttpHost("127.0.0.1", 8080))
.disableRedirectHandling()
// .disableCookieManagement()
;
if (url.startsWith("https://")) {
httpClientBuilder.setSSLSocketFactory(sslsf);
}
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = httpClientBuilder.build();
response = httpClient.execute(httpPost);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
}
} finally {
response.close();
httpClient.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static HttpClient createClient(SSLConnectionSocketFactory connectionFactory) {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
HttpClientBuilder httClientBuilder = HttpClients.custom();
if (connectionFactory != null) {
httClientBuilder = httClientBuilder.setSSLSocketFactory(connectionFactory);
}
HttpClient httpClient = httClientBuilder
.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
.setConnectionManager(cm).build();
cm.setMaxTotal(200); // Increase max total connection to 200
cm.setDefaultMaxPerRoute(20); // Increase default max connection per route to 20
return httpClient;
}
private HttpComponentsClientHttpRequestFactory generateHttpRequestFactory()
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException
{
TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
HttpClientBuilder httpClientBuilder = HttpClients.custom();
httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
CloseableHttpClient httpClient = httpClientBuilder.build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(httpClient);
return factory;
}
/**
* Utility method to create a {@link CloseableHttpClient} to make http POSTs against Splunk's
* HEC.
*
* @param maxConnections max number of parallel connections.
* @param disableCertificateValidation should disable certificate validation.
*/
private CloseableHttpClient getHttpClient(
int maxConnections, boolean disableCertificateValidation)
throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
HttpClientBuilder builder = ApacheHttpTransport.newDefaultHttpClientBuilder();
if (genericUrl().getScheme().equalsIgnoreCase(HTTPS_PROTOCOL_PREFIX)) {
LOG.info("SSL connection requested");
HostnameVerifier hostnameVerifier =
disableCertificateValidation
? NoopHostnameVerifier.INSTANCE
: new DefaultHostnameVerifier();
SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
if (disableCertificateValidation) {
LOG.info("Certificate validation is disabled");
sslContextBuilder.loadTrustMaterial((TrustStrategy) (chain, authType) -> true);
}
SSLConnectionSocketFactory connectionSocketFactory =
new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
builder.setSSLSocketFactory(connectionSocketFactory);
}
builder.setMaxConnTotal(maxConnections);
builder.setDefaultRequestConfig(
RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build());
return builder.build();
}
@Override
public CloseableHttpClient build() throws Exception {
HttpClientBuilder builder = HttpClients.custom();
builder.useSystemProperties();
builder
.setDefaultSocketConfig(SocketConfig.custom()
.setTcpNoDelay(true)
.setSoKeepAlive(true)
.build()
)
.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
HostnameVerifier hostnameVerifier = sslVerificationMode.verifier();
TrustStrategy trustStrategy = sslVerificationMode.trustStrategy();
KeyStore trustStore = agentTruststore();
SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
if (trustStore != null || trustStrategy != null) {
sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy);
}
KeyStore keystore = agentKeystore();
if (keystore != null) {
sslContextBuilder.loadKeyMaterial(keystore, agentKeystorePassword);
}
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
builder.setSSLSocketFactory(sslConnectionSocketFactory);
return builder.build();
}
private ClientHttpRequestFactory usingHttpComponents(ClientOptions options, SslConfiguration sslConfiguration)
throws GeneralSecurityException, IOException {
HttpClientBuilder httpClientBuilder = HttpClients.custom();
httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(
DefaultSchemePortResolver.INSTANCE, ProxySelector.getDefault()));
if (isNoneEmpty(httpsProxyUser, httpsProxyPassword)) {
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(httpsProxyUser, httpsProxyPassword);
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(AuthScope.ANY, credentials);
httpClientBuilder.setDefaultCredentialsProvider(provider);
}
if (hasSslConfiguration(sslConfiguration)) {
SSLContext sslContext = getSSLContext(sslConfiguration,
getTrustManagers(sslConfiguration));
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
sslContext);
httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
httpClientBuilder.setSSLContext(sslContext);
}
RequestConfig requestConfig = RequestConfig
.custom()
.setConnectTimeout(Math.toIntExact(options.getConnectionTimeout().toMillis()))
.setSocketTimeout(Math.toIntExact(options.getReadTimeout().toMillis()))
.setAuthenticationEnabled(true)
.build();
httpClientBuilder.setDefaultRequestConfig(requestConfig);
httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());
return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());
}
protected HttpClientBuilder clientBuilder(final URL nexusUrl, final boolean useCredentials) throws Exception {
HttpClientBuilder builder = HttpClients.custom();
builder.setDefaultRequestConfig(requestConfig());
if (useCredentials) {
doUseCredentials(nexusUrl, builder);
}
builder.setSSLSocketFactory(sslSocketFactory());
return builder;
}
public static CloseableHttpClient getHttpClient(HttpProtocol protocol) {
HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connMgr)
.setDefaultRequestConfig(requestConfig);
if (HttpProtocol.HTTPS.equals(protocol)) {
builder.setSSLSocketFactory(createSSLSocketFactory());
}
return builder.build();
}
static ClientHttpRequestFactory usingHttpComponents(ClientOptions options, SslConfiguration sslConfiguration)
throws GeneralSecurityException, IOException {
HttpClientBuilder httpClientBuilder = HttpClients.custom();
httpClientBuilder.setRoutePlanner(
new SystemDefaultRoutePlanner(DefaultSchemePortResolver.INSTANCE, ProxySelector.getDefault()));
if (hasSslConfiguration(sslConfiguration)) {
SSLContext sslContext = getSSLContext(sslConfiguration, getTrustManagers(sslConfiguration));
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
httpClientBuilder.setSSLContext(sslContext);
}
RequestConfig requestConfig = RequestConfig.custom()
//
.setConnectTimeout(Math.toIntExact(options.getConnectionTimeout().toMillis())) //
.setSocketTimeout(Math.toIntExact(options.getReadTimeout().toMillis())) //
.setAuthenticationEnabled(true) //
.build();
httpClientBuilder.setDefaultRequestConfig(requestConfig);
// Support redirects
httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());
return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());
}
protected void initClient(DatabricksServiceFactory.Builder builder) {
HttpClientBuilder clientBuilder = HttpClients.custom().useSystemProperties()
.setRetryHandler(retryHandler)
.setServiceUnavailableRetryStrategy(retryStrategy)
.setDefaultRequestConfig(createRequestConfig(builder));
List<Header> headers = new ArrayList<>();
if (isNotEmpty(builder.getToken())) {
Header authHeader = new BasicHeader("Authorization", String.format("Bearer %s", builder.getToken()));
headers.add(authHeader);
} else { // password authorization
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(host, HTTPS_PORT),
new UsernamePasswordCredentials(builder.getUsername(), builder.getPassword()));
clientBuilder.setDefaultCredentialsProvider(credsProvider);
}
String userAgent = builder.getUserAgent();
if (userAgent != null && userAgent.length() > 0) {
Header userAgentHeader = new BasicHeader("User-Agent", userAgent);
headers.add(userAgentHeader);
}
if (!headers.isEmpty()) {
clientBuilder.setDefaultHeaders(headers);
}
try {
SSLContext ctx = SSLContext.getDefault();
// Allow TLSv1.2 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
ctx,
new String[]{"TLSv1.2"},
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
clientBuilder = clientBuilder.setSSLSocketFactory(sslsf);
} catch (Exception e) {
logger.error("", e);
}
client = clientBuilder.build(); //CloseableHttpClient
url = String.format("https://%s/api/%s", host, apiVersion);
mapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
}
@Override
public void authenticate(HttpClientBuilder pBuilder, String pUser, String pPassword) {
pBuilder.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext));
super.authenticate(pBuilder, pUser, pPassword);
}
@Override
public HttpClient createHttpClient(FilterConfig filterConfig) {
final String serviceRole = filterConfig.getInitParameter(PARAMETER_SERVICE_ROLE);
HttpClientBuilder builder;
GatewayConfig gatewayConfig = (GatewayConfig) filterConfig.getServletContext().getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);
GatewayServices services = (GatewayServices) filterConfig.getServletContext()
.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
if (gatewayConfig != null && gatewayConfig.isMetricsEnabled()) {
MetricsService metricsService = services.getService(ServiceType.METRICS_SERVICE);
builder = metricsService.getInstrumented(HttpClientBuilder.class);
} else {
builder = HttpClients.custom();
}
// Conditionally set a custom SSLContext
SSLContext sslContext = createSSLContext(services, filterConfig, serviceRole);
if(sslContext != null) {
builder.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext));
}
if (Boolean.parseBoolean(System.getProperty(GatewayConfig.HADOOP_KERBEROS_SECURED))) {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UseJaasCredentials());
Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
.register(AuthSchemes.SPNEGO, new KnoxSpnegoAuthSchemeFactory(true))
.build();
builder.setDefaultAuthSchemeRegistry(authSchemeRegistry)
.setDefaultCookieStore(new HadoopAuthCookieStore(gatewayConfig))
.setDefaultCredentialsProvider(credentialsProvider);
} else {
builder.setDefaultCookieStore(new NoCookieStore());
}
builder.setKeepAliveStrategy( DefaultConnectionKeepAliveStrategy.INSTANCE );
builder.setConnectionReuseStrategy( DefaultConnectionReuseStrategy.INSTANCE );
builder.setRedirectStrategy( new NeverRedirectStrategy() );
builder.setRetryHandler( new NeverRetryHandler() );
int maxConnections = getMaxConnections( filterConfig );
builder.setMaxConnTotal( maxConnections );
builder.setMaxConnPerRoute( maxConnections );
builder.setDefaultRequestConfig(getRequestConfig(filterConfig, serviceRole));
// See KNOX-1530 for details
builder.disableContentCompression();
return builder.build();
}
private static HttpClient createHttpClient0(Settings settings, Path configPath) throws Exception {
HttpClientBuilder builder = HttpClients.custom();
builder.useSystemProperties();
SettingsBasedSSLConfigurator.SSLConfig sslConfig = getSSLConfig(settings, configPath);
if (sslConfig != null) {
builder.setSSLSocketFactory(sslConfig.toSSLConnectionSocketFactory());
}
return builder.build();
}