List of usage examples for org.apache.http.conn.ssl SSLSocketFactory SSLSocketFactory
public SSLSocketFactory(final javax.net.ssl.SSLSocketFactory socketfactory, final X509HostnameVerifier hostnameVerifier)
From source file:fr.ippon.wip.http.hc.HttpClientResourceManager.java
private HttpClientResourceManager() { perUserClientMap = Collections.synchronizedMap(new HashMap<String, HttpClient>()); perUserCookieStoreMap = Collections.synchronizedMap(new HashMap<String, CookieStore>()); perUserWindowCredentialProviderMap = Collections .synchronizedMap(new HashMap<String, CredentialsProvider>()); currentPortletRequest = new ThreadLocal<PortletRequest>(); currentPortletResponse = new ThreadLocal<PortletResponse>(); currentRequest = new ThreadLocal<RequestBuilder>(); try {/*from w w w . ja v a 2 s. c o m*/ SSLSocketFactory ssf = new SSLSocketFactory(new TrustSelfSignedStrategy(), new AllowAllHostnameVerifier()); Scheme httpsScheme = new Scheme("https", 443, ssf); PlainSocketFactory psf = new PlainSocketFactory(); Scheme httpScheme = new Scheme("http", 80, psf); SchemeRegistry registry = new SchemeRegistry(); registry.register(httpsScheme); registry.register(httpScheme); connectionManager = new PoolingClientConnectionManager(registry); connectionManager.setDefaultMaxPerRoute(10); connectionManager.setMaxTotal(100); DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connectionManager); // automatically redirects all HEAD, GET and POST requests defaultHttpClient.setRedirectStrategy(new LaxRedirectStrategy()); CacheConfig cacheConfig = createAndConfigureCache(); URL ehCacheConfig = getClass().getResource("/ehcache.xml"); cacheManager = CacheManager.create(ehCacheConfig); Ehcache ehcache = cacheManager.getEhcache("public"); EhcacheHttpCacheStorage httpCacheStorage = new EhcacheHttpCacheStorage(ehcache); CachingHttpClient sharedCacheClient = new CachingHttpClient(defaultHttpClient, httpCacheStorage, cacheConfig); HttpClientDecorator decoratedClient = new HttpClientDecorator(sharedCacheClient); decoratedClient.addPreProcessor(new LtpaRequestInterceptor()); decoratedClient.addPreProcessor(new StaleIfErrorRequestInterceptor(staleIfErrorTime)); decoratedClient.addFilter(new IgnoreHttpRequestFilter()); decoratedClient.addPostProcessor(new TransformerResponseInterceptor()); rootClient = decoratedClient; } catch (Exception e) { throw new RuntimeException("Could not initialize connection manager", e); } }
From source file:com.sinacloud.scs.http.HttpClientFactory.java
/** * Creates a new HttpClient object using the specified AWS * ClientConfiguration to configure the client. * * @param config// www .j av a2 s . co m * Client configuration options (ex: proxy settings, connection * limits, etc). * * @return The new, configured HttpClient. */ @SuppressWarnings("deprecation") public HttpClient createHttpClient(ClientConfiguration config) { /* Set HTTP client parameters */ HttpParams httpClientParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout()); HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout()); HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true); HttpConnectionParams.setTcpNoDelay(httpClientParams, true); int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0]; int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1]; if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) { HttpConnectionParams.setSocketBufferSize(httpClientParams, Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint)); } PoolingClientConnectionManager connectionManager = ConnectionManagerFactory .createPoolingClientConnManager(config, httpClientParams); SdkHttpClient httpClient = new SdkHttpClient(connectionManager, httpClientParams); if (config.getMaxErrorRetry() > 0) httpClient.setHttpRequestRetryHandler(SdkHttpRequestRetryHandler.Singleton); // httpClient.setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy()); try { Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80); SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(), SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); Scheme https = new Scheme("https", sf, 443); SchemeRegistry sr = connectionManager.getSchemeRegistry(); sr.register(http); sr.register(https); } catch (NoSuchAlgorithmException e) { throw new SCSClientException("Unable to access default SSL context", e); } // /* // * If SSL cert checking for endpoints has been explicitly disabled, // * register a new scheme for HTTPS that won't cause self-signed certs to // * error out. // */ // if (System.getProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) { Scheme sch = new Scheme("https", 443, new TrustingSocketFactory()); httpClient.getConnectionManager().getSchemeRegistry().register(sch); // } /* Set proxy if configured */ String proxyHost = config.getProxyHost(); int proxyPort = config.getProxyPort(); if (proxyHost != null && proxyPort > 0) { // AmazonHttpClient.log.info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort); HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost); String proxyUsername = config.getProxyUsername(); String proxyPassword = config.getProxyPassword(); String proxyDomain = config.getProxyDomain(); String proxyWorkstation = config.getProxyWorkstation(); if (proxyUsername != null && proxyPassword != null) { httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain)); } } return httpClient; }
From source file:nl.esciencecenter.osmium.JobLauncherService.java
/** * Enable insecure SSL in http client like self signed certificates. * * @param httpClient http client with secure SSL enabled * @throws NoSuchAlgorithmException when a particular cryptographic algorithm is requested but is not available in the environment. * @throws KeyManagementException if key management fails * @throws KeyStoreException if key store fails * @throws UnrecoverableKeyException if key is unrecoverable */// w ww. j a va 2 s . c o m public void useInsecureSSL(HttpClient httpClient) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { SSLSocketFactory socketFactory; socketFactory = new SSLSocketFactory(new TrustStrategy() { public boolean isTrusted(final X509Certificate[] chain, String authType) throws CertificateException { // Oh, I am easy... return true; } }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry registry = httpClient.getConnectionManager().getSchemeRegistry(); registry.register(new Scheme("https", HTTPS_PORT, socketFactory)); }
From source file:com.farmafene.commons.cas.HttpClientFactory.java
public DefaultHttpClient getClient() throws IllegalArgumentException { DefaultHttpClient httpClient = null; URL u = null;//ww w . jav a 2 s. c o m try { u = new URL(loginURL.toLowerCase()); } catch (MalformedURLException e) { IllegalArgumentException ex = new IllegalArgumentException("Error", e); logger.error("Excepcion en el login", ex); throw ex; } if ("https".equals(u.getProtocol())) { SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[] { this }, new SecureRandom()); } catch (NoSuchAlgorithmException e) { IllegalArgumentException ex = new IllegalArgumentException("Error", e); logger.error("Excepcion en el login", ex); throw ex; } catch (KeyManagementException e) { IllegalArgumentException ex = new IllegalArgumentException("Error", e); logger.error("Excepcion en el login", ex); throw ex; } SSLSocketFactory sf = new SSLSocketFactory(sslContext, this); Scheme httpsScheme = new Scheme("https", u.getPort() == -1 ? HTTPS_DEFAULT_PORT : u.getPort(), sf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); Scheme httpScheme = new Scheme("http", HTTP_DEFAULT_PORT, new PlainSocketFactory()); schemeRegistry.register(httpScheme); ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry); httpClient = new DefaultHttpClient(cm); } else { httpClient = new DefaultHttpClient(); } if (null != proxyHost) { if (logger.isDebugEnabled()) { logger.debug("Existe proxy: " + this); } HttpHost proxy = new HttpHost(proxyHost, proxyPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } return httpClient; }
From source file:org.eclipse.lyo.client.oauth.sample.OAuthClient.java
private static void disableCertificateValidatation(HttpClient client) { try {/*from w w w .j av a2s . c o m*/ final SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }, new java.security.SecureRandom()); final SSLSocketFactory socketFactory = new SSLSocketFactory(sc, new X509HostnameVerifier() { public void verify(String string, SSLSocket ssls) throws IOException { } public void verify(String string, X509Certificate xc) throws SSLException { } public void verify(String string, String[] strings, String[] strings1) throws SSLException { } public boolean verify(String string, SSLSession ssls) { return true; } }); final Scheme https = new Scheme("https", 443, socketFactory); client.getConnectionManager().getSchemeRegistry().register(https); } catch (GeneralSecurityException e) { } }
From source file:ua.pp.msk.gradle.http.Client.java
private void init(URL targetURL, String user, String password) throws ClientSslException { this.targetUrl = targetURL; logger.debug("Initializing " + this.getClass().getName() + " with target URL " + targetURL.toString()); HttpHost htHost = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), targetUrl.getProtocol()); AuthCache aCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); aCache.put(htHost, basicAuth);//from w ww .j a v a 2 s. c om UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password); BasicCredentialsProvider cProvider = new BasicCredentialsProvider(); cProvider.setCredentials(new AuthScope(htHost), creds); logger.debug("Credential provider: " + cProvider.toString()); context = new BasicHttpContext(); ClientContextConfigurer cliCon = new ClientContextConfigurer(context); cliCon.setCredentialsProvider(cProvider); context.setAttribute(ClientContext.AUTH_CACHE, aCache); SSLSocketFactory sslConnectionSocketFactory = null; try { sslConnectionSocketFactory = new SSLSocketFactory(new TrustSelfSignedStrategy(), new NexusHostnameVerifier()); } catch (KeyManagementException ex) { logger.error("Cannot manage secure keys", ex); throw new ClientSslException("Cannot manage secure keys", ex); } catch (KeyStoreException ex) { logger.error("Cannot build SSL context due to KeyStore error", ex); throw new ClientSslException("Cannot build SSL context due to KeyStore error", ex); } catch (NoSuchAlgorithmException ex) { logger.error("Unsupported security algorithm", ex); throw new ClientSslException("Unsupported security algorithm", ex); } catch (UnrecoverableKeyException ex) { logger.error("Unrecoverable key", ex); throw new ClientSslException("Unrecoverrable key", ex); } DefaultHttpClient defClient = new DefaultHttpClient(); defClient.setRedirectStrategy(new NexusRedirectStrategy()); defClient.setCredentialsProvider(cProvider); Scheme https = new Scheme("https", 443, sslConnectionSocketFactory); defClient.getConnectionManager().getSchemeRegistry().register(https); defClient.setTargetAuthenticationStrategy(new TargetAuthenticationStrategy()); client = defClient; }
From source file:pt.lunacloud.http.HttpClientFactory.java
/** * Creates a new HttpClient object using the specified AWS * ClientConfiguration to configure the client. * * @param config/*from w w w.j ava 2 s .co m*/ * Client configuration options (ex: proxy settings, connection * limits, etc). * * @return The new, configured HttpClient. */ public HttpClient createHttpClient(ClientConfiguration config) { /* Form User-Agent information */ String userAgent = config.getUserAgent(); if (!(userAgent.equals(ClientConfiguration.DEFAULT_USER_AGENT))) { userAgent += ", " + ClientConfiguration.DEFAULT_USER_AGENT; } /* Set HTTP client parameters */ HttpParams httpClientParams = new BasicHttpParams(); HttpProtocolParams.setUserAgent(httpClientParams, userAgent); HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout()); HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout()); HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, false); HttpConnectionParams.setTcpNoDelay(httpClientParams, true); int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0]; int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1]; if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) { HttpConnectionParams.setSocketBufferSize(httpClientParams, Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint)); } /* Set connection manager */ ThreadSafeClientConnManager connectionManager = ConnectionManagerFactory .createThreadSafeClientConnManager(config, httpClientParams); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpClientParams); httpClient.setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy()); try { Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory()); SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(), SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); Scheme https = new Scheme("https", 443, sf); SchemeRegistry sr = connectionManager.getSchemeRegistry(); sr.register(http); sr.register(https); } catch (NoSuchAlgorithmException e) { throw new LunacloudClientException("Unable to access default SSL context"); } /* * If SSL cert checking for endpoints has been explicitly disabled, * register a new scheme for HTTPS that won't cause self-signed certs to * error out. */ if (System.getProperty("com.amazonaws.sdk.disableCertChecking") != null) { Scheme sch = new Scheme("https", 443, new TrustingSocketFactory()); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } /* Set proxy if configured */ String proxyHost = config.getProxyHost(); int proxyPort = config.getProxyPort(); if (proxyHost != null && proxyPort > 0) { AmazonHttpClient.log .info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort); HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost); String proxyUsername = config.getProxyUsername(); String proxyPassword = config.getProxyPassword(); String proxyDomain = config.getProxyDomain(); String proxyWorkstation = config.getProxyWorkstation(); if (proxyUsername != null && proxyPassword != null) { httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain)); } } return httpClient; }
From source file:org.apache.hadoop.gateway.jetty.JettyHttpsTest.java
@Test public void testHttps() throws Exception { int port = jetty.getConnectors()[0].getLocalPort(); String url = "https://localhost:" + port + "/"; System.out.println("Jetty HTTPS listenting on port " + port + ". Press any key to continue."); System.in.read();//from www.j av a 2 s . c om SSLContext ctx = SSLContext.getInstance("TLS"); KeyManager[] keyManagers = createKeyManagers("jks", "target/test-classes/client-keystore.jks", "horton"); TrustManager[] trustManagers = createTrustManagers("jks", "target/test-classes/client-truststore.jks", "horton"); ctx.init(keyManagers, trustManagers, new SecureRandom()); SSLSocketFactory socketFactory = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry schemes = new SchemeRegistry(); schemes.register(new Scheme("https", port, socketFactory)); ClientConnectionManager cm = new BasicClientConnectionManager(schemes); HttpClient client = new DefaultHttpClient(cm); HttpGet get = new HttpGet(url); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); client.execute(get).getEntity().writeTo(buffer); assertThat(buffer.toString(), equalTo("<html>Hello!</html>")); }
From source file:com.careerly.utils.HttpClientUtils.java
/** * ??https//ww w .ja va2 s . c o m * * @param base * @return */ private static HttpClient wrapHttpsClient(HttpClient base) { try { SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("https", 443, ssf)); registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(registry); return new DefaultHttpClient(mgr, base.getParams()); } catch (Exception ex) { ex.printStackTrace(); return null; } }