下面列出了怎么用org.apache.http.ssl.SSLContextBuilder的API类实例代码及写法,或者点击链接到github查看源代码。
@Before
public void setup() throws Exception {
this.server.setHandler(new CheckRequestHandler());
this.server.afterPropertiesSet();
this.server.start();
// Set dynamically chosen port
this.port = this.server.getPort();
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(new TrustSelfSignedStrategy());
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
builder.build(), NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(
socketFactory).build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory(httpclient);
this.restTemplate = new RestTemplate(requestFactory);
}
@Test
public final void givenHttpClientPost4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build();
final NoopHostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLHostnameVerifier(hostnameVerifier)
.setSSLSocketFactory(sslsf)
.build();
// new
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
httpClient.close();
}
public static void initPool() {
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register(
Dict.HTTP, PlainConnectionSocketFactory.getSocketFactory()).register(
Dict.HTTPS, sslsf).build();
poolConnManager = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
poolConnManager.setMaxTotal(500);
poolConnManager.setDefaultMaxPerRoute(200);
int socketTimeout = 10000;
int connectTimeout = 10000;
int connectionRequestTimeout = 10000;
requestConfig = RequestConfig.custom().setConnectionRequestTimeout(
connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(
connectTimeout).build();
httpClient = getConnection();
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
logger.error("init http client pool failed:", ex);
}
}
public static void enabledSSL() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", new PlainConnectionSocketFactory())
.register("https", sslConnectionSocketFactory)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(100);
client = HttpClients.custom()
.setSSLSocketFactory(sslConnectionSocketFactory)
.setConnectionManager(cm)
.build();
}
protected SSLContext generateSSLContext() {
SSLContextBuilder contextBuilder = SSLContexts.custom();
try {
if (getTrustStoreFile() != null) {
contextBuilder.loadTrustMaterial(getTrustStoreFile(), getTrustStorePassword(), getTrustStrategy());
}
if (getKeyStoreFile() != null) {
contextBuilder.loadKeyMaterial(getKeyStoreFile(), getKeyStorePassword(), getKeyPassword(), getPrivateKeyStrategy());
}
return contextBuilder.build();
} catch (GeneralSecurityException | IOException e) {
throw new RuntimeException("Unable to configure SSL", e);
}
}
/**
* 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;
}
private SSLContext createSSLContext(final SSLContextService service)
throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
if (StringUtils.isNotBlank(service.getTrustStoreFile())) {
final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
truststore.load(in, service.getTrustStorePassword().toCharArray());
}
sslContextBuilder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
}
if (StringUtils.isNotBlank(service.getKeyStoreFile())){
final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
keystore.load(in, service.getKeyStorePassword().toCharArray());
}
sslContextBuilder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
}
sslContextBuilder.useProtocol(service.getSslAlgorithm());
return sslContextBuilder.build();
}
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;
}
private void loadKeyMaterial(SSLContextBuilder sslContextBuilder) throws NoSuchAlgorithmException,
KeyStoreException, CertificateException, IOException, UnrecoverableKeyException {
if (config.getKeyStore() != null) {
sslContextBuilder.setKeyStoreType(config.getKeyStoreType()).setProtocol(config.getProtocol());
if (!config.getKeyStore().startsWith(SecurityUtils.SAFKEYRING)) {
loadKeystoreMaterial(sslContextBuilder);
} else {
loadKeyringMaterial(sslContextBuilder);
}
} else {
log.info("No key store is defined");
KeyStore emptyKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
emptyKeystore.load(null, null);
usedKeyStore = emptyKeystore;
sslContextBuilder.loadKeyMaterial(emptyKeystore, null);
}
}
private void loadKeystoreMaterial(SSLContextBuilder sslContextBuilder) throws UnrecoverableKeyException,
NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
if (config.getKeyStore() == null) {
apimlLog.log("org.zowe.apiml.common.keystoreNotDefined");
throw new HttpsConfigError("server.ssl.keyStore configuration parameter is not defined",
ErrorCode.KEYSTORE_NOT_DEFINED, config);
}
if (config.getKeyStorePassword() == null) {
apimlLog.log("org.zowe.apiml.common.keystorePasswordNotDefined");
throw new HttpsConfigError("server.ssl.keyStorePassword configuration parameter is not defined",
ErrorCode.KEYSTORE_PASSWORD_NOT_DEFINED, config);
}
log.info("Loading key store file: " + config.getKeyStore());
File keyStoreFile = new File(config.getKeyStore());
sslContextBuilder.loadKeyMaterial(keyStoreFile,
config.getKeyStorePassword() == null ? null : config.getKeyStorePassword().toCharArray(),
config.getKeyPassword() == null ? null : config.getKeyPassword().toCharArray());
}
private synchronized SSLContext createSecureSslContext() {
if (secureSslContext == null) {
log.debug("Protocol: {}", config.getProtocol());
SSLContextBuilder sslContextBuilder = SSLContexts.custom();
try {
loadTrustMaterial(sslContextBuilder);
loadKeyMaterial(sslContextBuilder);
secureSslContext = sslContextBuilder.build();
validateSslConfig();
return secureSslContext;
} catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException
| UnrecoverableKeyException | KeyManagementException e) {
apimlLog.log("org.zowe.apiml.common.sslContextInitializationError", e.getMessage());
throw new HttpsConfigError("Error initializing SSL Context: " + e.getMessage(), e,
ErrorCode.HTTP_CLIENT_INITIALIZATION_FAILED, config);
}
} else {
return secureSslContext;
}
}
private SSLConnectionSocketFactory createFactoryFromAgentConfig(ConsulConfig.AgentConfig agentConfig) {
try {
SSLContextBuilder sslContextBuilder = SSLContexts.custom();
if (agentConfig.trustStore.isPresent()) {
sslContextBuilder = sslContextBuilder
.loadTrustMaterial(readStore(agentConfig.trustStore.get(), agentConfig.trustStorePassword), null);
} else if (agentConfig.trustCerts) {
sslContextBuilder = sslContextBuilder.loadTrustMaterial(TrustAllStrategy.INSTANCE);
}
if (agentConfig.keyStore.isPresent()) {
String keyPassword = agentConfig.keyPassword.orElse(agentConfig.keyStorePassword.orElse(""));
sslContextBuilder = sslContextBuilder.loadKeyMaterial(
readStore(agentConfig.keyStore.get(), agentConfig.keyStorePassword), keyPassword.toCharArray());
}
return new SSLConnectionSocketFactory(sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE);
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | IOException | CertificateException
| UnrecoverableKeyException e) {
throw new RuntimeException(e);
}
}
private SSLConnectionSocketFactory createSSLContext() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustAllStrategy());
String keyStorePath=System.getProperty("javax.net.ssl.keyStore","");
if (StringUtils.isNotEmpty(keyStorePath)) {
String keyStorePassword=System.getProperty("javax.net.ssl.keyStorePassword","");
if (StringUtils.isNotEmpty(keyStorePassword)) {
String keystoreType=System.getProperty("javax.net.ssl.keyStoreType",KeyStore.getDefaultType());
LOG.debug("Reading keystore from {}",keyStorePath);
KeyStore ks = KeyStore.getInstance(keystoreType);
ks.load(new FileInputStream(new File(keyStorePath)), keyStorePassword.toCharArray());
builder.loadKeyMaterial(ks,keyStorePassword.toCharArray());
}
} else {
LOG.debug("NO javax.net.ssl.keyStore property.");
}
String [] tlsProts = getAcceptedTLSProtocols();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
builder.build(),
tlsProts,
null,
new NoopHostnameVerifier());
return sslsf;
}
public static PoolingHttpClientConnectionManager getConnctionManager(){
Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
try {
SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(
new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
new TrustAllHostNameVerifier());
socketFactoryRegistry = RegistryBuilder
.<ConnectionSocketFactory> create()
.register("http", new PlainConnectionSocketFactory())
.register("https", trustSelfSignedSocketFactory)
.build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
Data.logger.warn("", e);
}
PoolingHttpClientConnectionManager cm = (socketFactoryRegistry != null) ?
new PoolingHttpClientConnectionManager(socketFactoryRegistry):
new PoolingHttpClientConnectionManager();
// twitter specific options
cm.setMaxTotal(2000);
cm.setDefaultMaxPerRoute(200);
return cm;
}
public String notifyHunter(byte[] content) throws IOException {
try {
String request = new String(content);
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();
HttpClient httpclient = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpPost httpPost = new HttpPost("https://api"+hunterDomain.substring(hunterDomain.indexOf("."))+"/api/record_injection");
String json = "{\"request\": \""+request.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r\n", "\\n")+"\", \"owner_correlation_key\": \""+hunterKey+"\", \"injection_key\": \""+injectKey+"\"}";
StringEntity entity = new StringEntity(json);
entity.setContentType("applicaiton/json");
httpPost.setEntity(entity);
HttpResponse response = httpclient.execute(httpPost);
String responseString = new BasicResponseHandler().handleResponse(response);
return responseString;
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
Logger.getLogger(HunterRequest.class.getName()).log(Level.SEVERE, null, ex);
}
return "Error Notifying Probe Server!";
}
private static CloseableHttpClient getHttpClient() throws
KeyManagementException, NoSuchAlgorithmException,
KeyStoreException {
// Relax SSL Certificate check
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
return true;
}
}).build();
Registry<ConnectionSocketFactory> registry = RegistryBuilder
.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext,
NoopHostnameVerifier.INSTANCE)).build();
PoolingHttpClientConnectionManager connectionManager = new
PoolingHttpClientConnectionManager(registry);
return HttpClients.custom().setConnectionManager(connectionManager)
.build();
}
private CloseableHttpClient noSslHttpClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
final SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (x509CertChain, authType) -> true)
.build();
return HttpClientBuilder.create()
.setSSLContext(sslContext)
.setConnectionManager(
new PoolingHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext,
NoopHostnameVerifier.INSTANCE))
.build()
))
.build();
}
@Test
public void testCreate() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext sslContext = new SSLContextBuilder().build();
ClientOptions options = ClientOptions.builder()
.setConnectionPoolSizePerRoute(2)
.setConnectionPoolTotalSize(50)
.setConnectTimeout(100)
.setSocketTimeout(1000)
.setRetryCount(5)
.setSslContext(sslContext)
.setShardWidth(1024)
.build();
assertEquals(2, options.getConnectionPoolSizePerRoute());
assertEquals(50, options.getConnectionPoolTotalSize());
assertEquals(100, options.getConnectTimeout());
assertEquals(1000, options.getSocketTimeout());
assertEquals(5, options.getRetryCount());
assertEquals(sslContext, options.getSslContext());
assertEquals(1024, options.getShardWidth());
}
@Override
protected TTransport newTransport(String uri, HttpHeaders headers) throws TTransportException {
final SSLContext sslContext;
try {
sslContext = SSLContextBuilder.create()
.loadTrustMaterial((TrustStrategy) (chain, authType) -> true)
.build();
} catch (GeneralSecurityException e) {
throw new TTransportException("failed to initialize an SSL context", e);
}
final THttpClient client = new THttpClient(
uri, HttpClientBuilder.create()
.setSSLHostnameVerifier((hostname, session) -> true)
.setSSLContext(sslContext)
.build());
client.setCustomHeaders(
headers.names().stream()
.collect(toImmutableMap(AsciiString::toString,
name -> String.join(", ", headers.getAll(name)))));
return client;
}
private CloseableHttpClient createSslHttpClient() throws Exception {
final SSLContextBuilder wsBuilder = new SSLContextBuilder();
wsBuilder.loadTrustMaterial(null, (chain, authType) -> true);
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(wsBuilder.build(),
new NoopHostnameVerifier());
//This winds up using a PoolingHttpClientConnectionManager so need to pass the
//RegistryBuilder
final Registry<ConnectionSocketFactory> registry = RegistryBuilder
.<ConnectionSocketFactory> create().register("https", sslsf)
.build();
final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
return HttpClients
.custom()
.setConnectionManager(cm)
.build();
}
/**
* custom http client for server with SSL errors
*
* @return
*/
public final CloseableHttpClient getCustomClient() {
try {
HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
(TrustStrategy) (X509Certificate[] arg0, String arg1) -> true).build();
builder.setSSLContext(sslContext);
HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
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);
builder.setConnectionManager(connMgr);
return builder.build();
} catch (Exception ex) {
LOG.log(Level.SEVERE, ex.getMessage(), ex);
}
return getSystemClient();
}
@Override
public CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
LOGGER.info("###Used SSL Enabled Http Client with Corporate Proxy, for both Http and Https connections");
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (certificate, authType) -> true).build();
CookieStore cookieStore = new BasicCookieStore();
CredentialsProvider credsProvider = createProxyCredentialsProvider(proxyHost, proxyPort, proxyUserName, proxyPassword);
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
return HttpClients.custom()
.setSSLContext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.setDefaultCookieStore(cookieStore)
.setDefaultCredentialsProvider(credsProvider)
.setProxy(proxy)
.build();
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) throws Exception {
SSLContext sslContext = SSLContextBuilder
.create()
.loadKeyMaterial(ResourceUtils.getFile("classpath:keystore.jks"), allPassword, allPassword)
.loadTrustMaterial(ResourceUtils.getFile("classpath:truststore.jks"), allPassword)
.build();
HttpClient client = HttpClients.custom()
.setSSLContext(sslContext)
.build();
return builder
.requestFactory(new HttpComponentsClientHttpRequestFactory(client))
.build();
}
@Test
public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception {
final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true)
.build();
final CloseableHttpClient client = HttpClients.custom()
.setSSLContext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
final HttpGet httpGet = new HttpGet(HOST_WITH_SSL);
httpGet.setHeader("Accept", "application/xml");
final HttpResponse response = client.execute(httpGet);
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
}
public static SSLConnectionSocketFactory createSocketFactory(Path truststoreFile, Path keystoreFile, String password)
throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException {
final char[] pwd = password.toCharArray();
SSLContextBuilder sslcontextBuilder = SSLContexts.custom()
.loadTrustMaterial(truststoreFile.toFile(), pwd, TrustSelfSignedStrategy.INSTANCE)
;
if (keystoreFile != null) {
sslcontextBuilder.loadKeyMaterial(keystoreFile.toFile(), pwd, pwd);
}
sslcontextBuilder.setProtocol("TLSv1.2");
return new SSLConnectionSocketFactory(sslcontextBuilder.build(), new HostnameVerifier() {
@Override
public boolean verify(final String s, final SSLSession sslSession) {
return true;
}
});
}
public CustomHttpClient(String url, String user, String pass) throws Exception {
this.openviduUrl = url.replaceFirst("/*$", "");
this.headerAuth = "Basic " + Base64.getEncoder().encodeToString((user + ":" + pass).getBytes());
SSLContext sslContext = null;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
throw new Exception("Error building custom HttpClient: " + e.getMessage());
}
HttpClient unsafeHttpClient = HttpClients.custom().setSSLContext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
Unirest.setHttpClient(unsafeHttpClient);
}
/**
* This method has been overridden here simply to show how a custom/project-specific http client
* can be plugged into the framework.
*
* e.g. You can create your own project specific http client needed for http/https/tls connections or
* a Corporate proxy based Http client here.
* Sometimes you may need a simple default http client
* e.g. HttpClients.createDefault() provided by Apache lib.
*
* Note:
* If you do not override this method, the framework anyways creates a http client suitable for both http/https.
*/
@Override
public CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
LOGGER.info("###Used SSL Enabled Http Client for http/https/TLS connections");
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (certificate, authType) -> true).build();
CookieStore cookieStore = new BasicCookieStore();
return HttpClients.custom()
.setSSLContext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.setDefaultCookieStore(cookieStore)
.build();
}
/**
* 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();
}
}
private static SSLContextBuilder loadKeyMaterial(SSLContextBuilder builder, File file, char[] ksp,
char[] kp, PrivateKeyStrategy privateKeyStrategy) throws NoSuchAlgorithmException,
KeyStoreException, UnrecoverableKeyException, CertificateException, IOException {
Args.notNull(file, "Keystore file"); //$NON-NLS-1$
final KeyStore identityStore = KeyStore.getInstance(KeyStore.getDefaultType());
final FileInputStream instream = new FileInputStream(file);
try {
identityStore.load(instream, ksp);
} finally {
instream.close();
}
return builder.loadKeyMaterial(identityStore, kp, privateKeyStrategy);
}