List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory
public SSLConnectionSocketFactory(final javax.net.ssl.SSLSocketFactory socketfactory, final X509HostnameVerifier hostnameVerifier)
From source file:com.sonatype.nexus.ssl.plugin.internal.CertificateRetriever.java
/** * Retrieves certificate chain of specified host:port using https protocol. * * @param host to get certificate chain from (cannot be null) * @param port of host to connect to/*w w w. j a va2s.c o m*/ * @return certificate chain * @throws Exception Re-thrown from accessing the remote host */ public Certificate[] retrieveCertificatesFromHttpsServer(final String host, final int port) throws Exception { checkNotNull(host); log.info("Retrieving certificate from https://{}:{}", host, port); // setup custom connection manager so we can configure SSL to trust-all SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, new TrustManager[] { ACCEPT_ALL_TRUST_MANAGER }, null); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sc, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register(HttpSchemes.HTTP, PlainConnectionSocketFactory.getSocketFactory()) .register(HttpSchemes.HTTPS, sslSocketFactory).build(); final HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(registry); try { final AtomicReference<Certificate[]> certificates = new AtomicReference<>(); HttpClient httpClient = httpClientManager.create(new Customizer() { @Override public void customize(final HttpClientPlan plan) { // replace connection-manager with customized version needed to fetch SSL certificates plan.getClient().setConnectionManager(connectionManager); // add interceptor to grab peer-certificates plan.getClient().addInterceptorFirst(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { ManagedHttpClientConnection connection = HttpCoreContext.adapt(context) .getConnection(ManagedHttpClientConnection.class); // grab the peer-certificates from the session if (connection != null) { SSLSession session = connection.getSSLSession(); if (session != null) { certificates.set(session.getPeerCertificates()); } } } }); } }); httpClient.execute(new HttpGet("https://" + host + ":" + port)); return certificates.get(); } finally { // shutdown single-use connection manager connectionManager.shutdown(); } }
From source file:majordodo.client.http.Client.java
private void createClient() { try {/* w w w . j av a 2s. co m*/ SSLContext sslContext; SSLConnectionSocketFactory sslsf; if (configuration.isDisableHttpsVerification()) { sslContext = SSLContext.getInstance("SSL"); TrustManager mytm[] = { new MyTrustManager() }; sslContext.init(null, mytm, null); sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } else { sslContext = SSLContexts.custom().build(); sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", new PlainConnectionSocketFactory()).register("https", sslsf).build(); poolManager = new PoolingHttpClientConnectionManager(r); if (configuration.getMaxConnTotal() > 0) { poolManager.setMaxTotal(configuration.getMaxConnTotal()); } if (configuration.getMaxConnPerRoute() > 0) { poolManager.setDefaultMaxPerRoute(configuration.getMaxConnPerRoute()); } poolManager.setDefaultSocketConfig(SocketConfig.custom().setSoKeepAlive(true).setSoReuseAddress(true) .setTcpNoDelay(false).setSoTimeout(configuration.getSotimeout()).build()); ConnectionKeepAliveStrategy myStrategy = (HttpResponse response, HttpContext context) -> configuration .getKeepAlive(); httpclient = HttpClients.custom().setConnectionManager(poolManager) .setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE) .setKeepAliveStrategy(myStrategy).build(); } catch (NoSuchAlgorithmException | KeyManagementException ex) { throw new RuntimeException(ex); } }
From source file:sample.tomcat.X509ApplicationTests.java
private SSLConnectionSocketFactory socketFactory() throws Exception { char[] password = "password".toCharArray(); KeyStore truststore = KeyStore.getInstance("PKCS12"); truststore.load(getKeyStoreFile(), password); SSLContextBuilder builder = new SSLContextBuilder(); builder.loadKeyMaterial(truststore, password); builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy()); return new SSLConnectionSocketFactory(builder.build(), new AllowAllHostnameVerifier()); }
From source file:com.activiti.service.activiti.ActivitiClientService.java
public CloseableHttpClient getHttpClient(String userName, String password) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password)); SSLConnectionSocketFactory sslsf = null; try {//from w ww. ja v a 2 s. c o m SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslsf = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (Exception e) { log.warn("Could not configure HTTP client to use SSL", e); } HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); if (sslsf != null) { httpClientBuilder.setSSLSocketFactory(sslsf); } return httpClientBuilder.build(); }
From source file:ch.cyberduck.core.http.HttpConnectionPoolBuilder.java
public HttpConnectionPoolBuilder(final Host host, final ThreadLocalHostnameDelegatingTrustManager trust, final X509KeyManager key, final ProxyFinder proxy) { this(host, new PlainConnectionSocketFactory() { @Override//from w w w . j a v a 2s. c o m public Socket createSocket(final HttpContext context) throws IOException { // Return socket factory with disabled support for HTTP tunneling as provided internally return new ProxySocketFactory(host.getProtocol(), new TrustManagerHostnameCallback() { @Override public String getTarget() { return context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST).toString(); } }, proxy).disable(Proxy.Type.HTTP).disable(Proxy.Type.HTTPS).createSocket(); } }, new SSLConnectionSocketFactory(new CustomTrustSSLProtocolSocketFactory(trust, key), new DisabledX509HostnameVerifier()) { @Override public Socket createSocket(final HttpContext context) throws IOException { return new ProxySocketFactory(host.getProtocol(), new TrustManagerHostnameCallback() { @Override public String getTarget() { return context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST).toString(); } }, proxy).disable(Proxy.Type.HTTP).disable(Proxy.Type.HTTPS).createSocket(); } @Override public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException { trust.setTarget(remoteAddress.getHostName()); return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context); } }, proxy); }
From source file:org.jboss.arquillian.ce.httpclient.HttpClientBuilder.java
public HttpClientBuilder untrustedConnectionClientBuilder() throws Exception { // setup a Trust Strategy that allows all certificates. ////w ww. j av a 2 s . c o m SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { return true; } }).build(); builder.setSslcontext(sslContext); // 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, (X509HostnameVerifier) 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); builder.setConnectionManager(connMgr); // finally, build the HttpClient; // -- done! return this; }
From source file:com.emc.storageos.driver.dellsc.scapi.rest.RestClient.java
/** * Instantiates a new Rest client.//from w w w.ja va2s . c o m * * @param host Host name or IP address of the Dell Storage Manager server. * @param port Port the DSM data collector is listening on. * @param user The DSM user name to use. * @param password The DSM password. */ public RestClient(String host, int port, String user, String password) { this.baseUrl = String.format("https://%s:%d/api/rest", host, port); try { // Set up auth handling CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(user, password)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); HttpHost target = new HttpHost(host, port, "https"); authCache.put(target, basicAuth); // Set up our context httpContext = HttpClientContext.create(); httpContext.setCookieStore(new BasicCookieStore()); httpContext.setAuthCache(authCache); // Create our HTTPS client SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); this.httpClient = HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier()) .setDefaultCredentialsProvider(credsProvider).setSSLSocketFactory(sslSocketFactory).build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { // Hopefully default SSL handling is set up LOG.warn("Failed to configure HTTP handling, falling back to default handler."); LOG.debug("Config error: {}", e); this.httpClient = HttpClients.createDefault(); } }
From source file:net.ymate.platform.module.wechat.support.HttpClientHelper.java
private CloseableHttpClient __doBuildHttpClient() throws KeyManagementException, NoSuchAlgorithmException { HttpClientBuilder _builder = HttpClientBuilder.create() .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(__connectionTimeout) .setSocketTimeout(__connectionTimeout).setConnectionRequestTimeout(__connectionTimeout) .build());//from ww w. j a v a 2 s.co m if (__socketFactory == null) { __socketFactory = new SSLConnectionSocketFactory(SSLContexts.custom().useSSL().build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } return _builder.setSSLSocketFactory(__socketFactory).build(); }