下面列出了怎么用org.apache.http.ssl.TrustStrategy的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Rest template setup including a disabled SSL certificate validation.
* @throws Exception in case of errors
*/
private static void setupRestTemplate() throws Exception {
final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
final SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
final HttpClient httpClient = HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy())
.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
.build();
factory.setHttpClient(httpClient);
restTemplate.setRequestFactory(factory);
for (int i = 0; i < restTemplate.getMessageConverters().size(); i++) {
if (restTemplate.getMessageConverters().get(i) instanceof StringHttpMessageConverter) {
restTemplate.getMessageConverters().set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8));
break;
}
}
}
/**
* Gets the http client.
*
* @return the http client
*/
private static CloseableHttpClient getHttpClient() {
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build()).build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
LOGGER.error("Error getting getHttpClient " , e);
}
return httpClient;
}
/**
* Gets the http client.
*
* @return the http client
*/
private static CloseableHttpClient getHttpClient() {
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build()).build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
LOGGER.error("Error getting getHttpClient " , e);
}
return httpClient;
}
/**
* Gets the http client.
*
* @return the http client
*/
private static CloseableHttpClient getHttpClient() {
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build()).build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
LOGGER.error("Error getting getHttpClient " , e);
}
return httpClient;
}
public GerritChecksApiBuilder allowInsecureHttps() {
try {
SSLContext sslContext =
new SSLContextBuilder()
.loadTrustMaterial(
null,
new TrustStrategy() {
public boolean isTrusted(final X509Certificate[] chain, String authType)
throws CertificateException {
return true;
}
})
.build();
SSLConnectionSocketFactory sslsf =
new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
clientBuilder.setSSLSocketFactory(sslsf);
} catch (KeyStoreException | KeyManagementException | NoSuchAlgorithmException e) {
LOGGER.log(Level.WARNING, "Could not disable SSL verification.", e);
}
return this;
}
/**
* Will create a certificate-ignoring {@link SSLContext}. Please use with utmost caution as it undermines security,
* but may be useful in certain testing or development scenarios.
*
* @return The SSLContext
*/
public static SSLContext buildCertificateIgnoringSslContext() {
try {
return SSLContexts
.custom()
.loadTrustMaterial(new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
})
.build();
}
catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
throw new IllegalStateException("Unexpected exception while building the certificate-ignoring SSLContext.", e);
}
}
/**
* 创建SSL安全连接
*
* @return
*/
private static SSLConnectionSocketFactory createSSLSocketFactory() {
try {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,
NoopHostnameVerifier.INSTANCE);
// new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1"}, null, NoopHostnameVerifier.INSTANCE);
return socketFactory;
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
throw new IllegalStateException("Unexpected exception while building the certificate-ignoring SSLContext.",
e);
}
}
/**
* 创建SSL安全连接
*
* @return
*/
private static SSLConnectionSocketFactory createSSLSocketFactory() {
try {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,
NoopHostnameVerifier.INSTANCE);
// new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1"}, null, NoopHostnameVerifier.INSTANCE);
return socketFactory;
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
throw new IllegalStateException("Unexpected exception while building the certificate-ignoring SSLContext.",
e);
}
}
/**
* This creates a HTTP client instance for connecting the IFTTT server.
*
* @return the HTTP client instance
*/
private CloseableHttpClient buildHttpClient ()
{
if ( configuration.isIftttIgnoreServerCertificate() ) {
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(new TrustStrategy() {
@Override
public boolean isTrusted (X509Certificate[] chain_, String authType_) throws CertificateException
{
return true;
}
});
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
catch (Exception ex) {
LOG.error(ex);
// This should never happen, but we have to handle it
throw new RuntimeException(ex);
}
}
else {
return HttpClients.createDefault();
}
}
public WebhookService()
throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException
{
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain,
String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
nonValidatingRequestFactory = new HttpComponentsClientHttpRequestFactory();
nonValidatingRequestFactory.setHttpClient(httpClient);
}
private CloseableHttpClient getCarelessHttpClient(boolean disableRedirect) {
CloseableHttpClient httpClient = null;
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
});
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
HttpClientBuilder httpClientBuilder = HttpClients
.custom()
.setSSLSocketFactory(sslsf);
if (disableRedirect) {
httpClientBuilder.disableRedirectHandling();
}
httpClientBuilder.setUserAgent("swagger-validator");
httpClient = httpClientBuilder.build();
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
LOGGER.error("can't disable SSL verification", e);
}
return httpClient;
}
public HttpHelper(){
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setMaxConnPerRoute(50);
builder.setMaxConnTotal(100);
// 创建支持忽略证书的https
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();
httpclient = HttpClientBuilder.create()
.setSSLContext(sslContext)
.setConnectionManager(new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
.build()))
.build();
} catch (Throwable e) {
// ignore
}
}
public void initialize(NettyRpcProperties properties, boolean https) throws Exception {
CommonProperties cp = properties.getCommonProperties();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(Integer.parseInt(cp.getHttpConnectTimeout()))
.setConnectionRequestTimeout(Integer.parseInt(cp.getHttpConnectRequestTimeout()))
.setSocketTimeout(Integer.parseInt(cp.getHttpSocketTimeout()))
.build();
HttpClientBuilder clientBuilder = HttpClients.custom();
clientBuilder.setDefaultRequestConfig(requestConfig);
if (https) {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
clientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);
}
httpSyncClient = clientBuilder.build();
LOG.info("Create apache sync client with {} successfully", https ? "https mode" : "http mode");
}
private static CloseableHttpClient getHttpClient() {
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build()).build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
log.error("Error in HttpUtil post ", e);
}
return httpClient;
}
/**
* Gets the http client.
*
* @return the http client
*/
private static CloseableHttpClient getHttpClient() {
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build()).build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
LOGGER.error("Error getting getHttpClient " , e);
}
return httpClient;
}
private static CloseableHttpClient getHttpClient() {
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build()).build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
log.error("Error in HttpUtil post ", e);
}
return httpClient;
}
public void initialize(boolean https) throws Exception {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(Integer.parseInt(HTTPCLIENT_CONNCT_TIMEOUT_DEFAULT))
.setConnectionRequestTimeout(Integer.parseInt(HTTPCLIENT_CONNCT_REQUEST_TIMEOUT_DEFAULT))
.setSocketTimeout(Integer.parseInt(HTTPCLIENT_SOCKET_TIMEOUT_DEFAULT))
.build();
HttpClientBuilder clientBuilder = HttpClients.custom();
clientBuilder.setDefaultRequestConfig(requestConfig);
if (https) {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
clientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);
}
httpSyncClient = clientBuilder.build();
LOG.info("Create apache sync client with {} successfully", https ? "https mode" : "http mode");
}
public HttpClientConnectionManager createHttpClientConnectionManager() {
SSLContext sslContext = null;
try {
sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return false;
}
}).build();
} catch (Exception e) {
throw new RuntimeException(e);
}
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory)
.build();
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
// 最大连接数
poolingHttpClientConnectionManager.setMaxTotal(httpClientConfig.getMaxTotal());
// 单个站点最大连接数
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(httpClientConfig.getMaxPerRoute());
// 长连接
poolingHttpClientConnectionManager.setDefaultSocketConfig(
SocketConfig.custom().setSoTimeout(httpClientConfig.getSocketTimeout()).setSoKeepAlive(true).build());
// 连接不活跃多久检查毫秒 并不是100 % 可信
poolingHttpClientConnectionManager.setValidateAfterInactivity(httpClientConfig.getValidateAfterInactivity());
// 空闲扫描线程
HttpClientIdleConnectionMonitor.registerConnectionManager(poolingHttpClientConnectionManager, httpClientConfig);
return poolingHttpClientConnectionManager;
}
private Registry constructRegistry() {
try {
SSLContextBuilder builder = SSLContextBuilder.create();
builder.useProtocol(this.supportedProtocols[0]);
if (!StringUtils.isNullOrEmpty(clientConfigurator.getCertificateFileName())) {
builder.loadKeyMaterial(SslUtils.loadKeystore(clientConfigurator.getCertificateFileName(),
clientConfigurator.getCertificateFilePassword()),
clientConfigurator.getCertificateFilePassword().toCharArray());
}
// Trust all certificates
builder.loadTrustMaterial(new TrustStrategy() {
@Override
public boolean isTrusted( X509Certificate[] chain, String authType ) throws CertificateException {
return true;
}
});
SSLContext sslContext = builder.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
new NoopHostnameVerifier());
Registry registry = RegistryBuilder.create().register("https", sslsf).build();
return registry;
} catch (Exception e) {
throw new RuntimeException("Unable to setup SSL context for REST client with Apache connector provider", e);
}
}
/**
* @param urlOpenViduServer Public accessible IP where your instance of OpenVidu
* Server is up an running
* @param secret Secret used on OpenVidu Server initialization
*/
public OpenVidu(String hostname, String secret) {
this.hostname = hostname;
if (!this.hostname.endsWith("/")) {
this.hostname += "/";
}
this.secret = secret;
TrustStrategy trustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
};
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("OPENVIDUAPP", this.secret);
provider.setCredentials(AuthScope.ANY, credentials);
SSLContext sslContext;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
throw new RuntimeException(e);
}
RequestConfig.Builder requestBuilder = RequestConfig.custom();
requestBuilder = requestBuilder.setConnectTimeout(30000);
requestBuilder = requestBuilder.setConnectionRequestTimeout(30000);
this.httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestBuilder.build())
.setConnectionTimeToLive(30, TimeUnit.SECONDS).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.setSSLContext(sslContext).setDefaultCredentialsProvider(provider).build();
}
public HttpWebhookSender(String httpEndpoint, List<Header> headers, List<CDREventName> events) {
this.httpEndpoint = httpEndpoint;
this.events = events;
this.customHeaders = new ArrayList<>();
boolean contentTypeHeaderAdded = false;
for (Header header : headers) {
this.customHeaders.add(header);
if (!contentTypeHeaderAdded && HttpHeaders.CONTENT_TYPE.equals(header.getName())
&& "application/json".equals(header.getValue())) {
contentTypeHeaderAdded = true;
}
}
if (!contentTypeHeaderAdded) {
this.customHeaders.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
}
TrustStrategy trustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
};
SSLContext sslContext;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
throw new RuntimeException(e);
}
RequestConfig.Builder requestBuilder = RequestConfig.custom();
requestBuilder = requestBuilder.setConnectTimeout(30000);
requestBuilder = requestBuilder.setConnectionRequestTimeout(30000);
this.httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestBuilder.build())
.setConnectionTimeToLive(30, TimeUnit.SECONDS).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.setSSLContext(sslContext).build();
}
public void initialize(ThunderProperties properties, boolean https) throws Exception {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(properties.getInteger(ThunderConstant.APACHE_CONNECT_TIMEOUT_ATTRIBUTE_NAME))
.setConnectionRequestTimeout(properties.getInteger(ThunderConstant.APACHE_CONNECT_TIMEOUT_ATTRIBUTE_NAME))
.setSocketTimeout(properties.getInteger(ThunderConstant.APACHE_SO_TIMEOUT_ATTRIBUTE_NAME))
.build();
HttpClientBuilder clientBuilder = HttpClients.custom();
clientBuilder.setDefaultRequestConfig(requestConfig);
if (https) {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
clientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);
}
httpSyncClient = clientBuilder.build();
LOG.info("Create apache sync client with {} successfully", https ? "https mode" : "http mode");
}
private static HttpClient createHttpClient()
throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
HttpClientBuilder b = HttpClientBuilder.create();
// setup a Trust Strategy that allows all certificates.
//
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
b.setSSLContext(sslContext);
//b.setSSLHostnameVerifier(new NoopHostnameVerifier());
// don't check Hostnames, either.
// -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
// here's the special part:
// -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
// -- and create a Registry, to register it.
//
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
// now, we create connection-manager using our Registry.
// -- allows multi-threaded use
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
b.setConnectionManager(connMgr);
// finally, build the HttpClient;
// -- done!
CloseableHttpClient client = b.build();
return client;
}
private static HttpClient createHttpClient()
throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
HttpClientBuilder b = HttpClientBuilder.create();
// setup a Trust Strategy that allows all certificates.
//
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
b.setSSLContext(sslContext);
//b.setSSLHostnameVerifier(new NoopHostnameVerifier());
// don't check Hostnames, either.
// -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
// here's the special part:
// -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
// -- and create a Registry, to register it.
//
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
// now, we create connection-manager using our Registry.
// -- allows multi-threaded use
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
b.setConnectionManager(connMgr);
// finally, build the HttpClient;
// -- done!
CloseableHttpClient client = b.build();
return client;
}
/**
* Create a {@link CloseableHttpClient} used to communicate with Azkaban server.
* Derived class can configure different http client by overriding this method.
*
* @return A closeable http client.
*/
private CloseableHttpClient createHttpClient() throws AzkabanClientException {
try {
// SSLSocketFactory using custom TrustStrategy that ignores warnings about untrusted certificates
// Self sign SSL
SSLContextBuilder sslcb = new SSLContextBuilder();
sslcb.loadTrustMaterial(null, (TrustStrategy) new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcb.build());
HttpClientBuilder builder = HttpClientBuilder.create();
RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT)
.setSocketTimeout(10000)
.setConnectTimeout(10000)
.setConnectionRequestTimeout(10000)
.build();
builder.disableCookieManagement()
.useSystemProperties()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(new BasicHttpClientConnectionManager())
.setSSLSocketFactory(sslsf);
return builder.build();
} catch (Exception e) {
throw new AzkabanClientException("HttpClient cannot be created", e);
}
}
private static CloseableHttpClient getHttpClient()
throws IOException {
try {
// Self sign SSL
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, (TrustStrategy) new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
// Create client
return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCookieStore(new BasicCookieStore()).build();
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
throw new IOException("Issue with creating http client", e);
}
}
CloseableHttpClient getHttpClient() {
// TODO: set a timeout until we have a proper way to deal with back pressure
int timeout = 5;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout * 1000)
.setConnectionRequestTimeout(timeout * 1000)
.setSocketTimeout(timeout * 1000).build();
final TrustStrategy trustAllStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) {
return true;
}
};
try {
if(!verifySSL) {
return HttpClients.custom()
.setSSLSocketFactory(
new SSLConnectionSocketFactory(
new SSLContextBuilder()
.loadTrustMaterial(trustAllStrategy)
.build(),
NoopHostnameVerifier.INSTANCE))
.setDefaultRequestConfig(config)
.build();
}
if(effectiveTruststore == null) {
return HttpClients.custom()
.setDefaultRequestConfig(config)
.build();
}
return HttpClients.custom()
.setSSLSocketFactory(
new SSLConnectionSocketFactory(
new SSLContextBuilder()
.loadTrustMaterial(effectiveTruststore, null)
.build(),
new DefaultHostnameVerifier()))
.setDefaultRequestConfig(config)
.build();
} catch(Exception ex) {
log.error("Could not create HTTPClient due to {}, audit log not available.", ex.getMessage(), ex);
return null;
}
}
private void download(BinlogFile binlogFile) throws Throwable {
String downloadLink = binlogFile.getDownloadLink();
String fileName = binlogFile.getFileName();
downloadLink = downloadLink.trim();
CloseableHttpClient httpClient = null;
if (downloadLink.startsWith("https")) {
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setMaxConnPerRoute(50);
builder.setMaxConnTotal(100);
// 创建支持忽略证书的https
final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();
httpClient = HttpClientBuilder.create()
.setSSLContext(sslContext)
.setConnectionManager(new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
.build()))
.build();
} else {
httpClient = HttpClientBuilder.create().setMaxConnPerRoute(50).setMaxConnTotal(100).build();
}
HttpGet httpGet = new HttpGet(downloadLink);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(TIMEOUT)
.setConnectionRequestTimeout(TIMEOUT)
.setSocketTimeout(TIMEOUT)
.build();
httpGet.setConfig(requestConfig);
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpResponseStatus.OK.code()) {
throw new RuntimeException("download failed , url:" + downloadLink + " , statusCode:" + statusCode);
}
saveFile(new File(destDir), "mysql-bin." + fileName, response);
}
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;
}
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;
}