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:gov.nih.nci.nbia.StandaloneDMV3.java
private List<String> connectAndReadFromURL(URL url, List<String> seriesList, String userId, String passWd) { List<String> data = null; DefaultHttpClient httpClient = null; TrustStrategy easyStrategy = new TrustStrategy() { @Override//from ww w .j a v a 2 s. c o m public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException { return true; } }; try { // SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything // sslContext.init(null, new TrustManager[] { new // EasyX509TrustManager(null)}, null); SSLSocketFactory sslsf = new SSLSocketFactory(easyStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme httpsScheme = new Scheme("https", 443, sslsf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); ClientConnectionManager ccm = new ThreadSafeClientConnManager(schemeRegistry); HttpParams httpParams = new BasicHttpParams(); // HttpConnectionParams.setConnectionTimeout(httpParams, 50000); // HttpConnectionParams.setSoTimeout(httpParams, new // Integer(12000)); HttpConnectionParams.setConnectionTimeout(httpParams, 500000); HttpConnectionParams.setSoTimeout(httpParams, new Integer(120000)); httpClient = new DefaultHttpClient(ccm, httpParams); httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(schemeRegistry, ProxySelector.getDefault())); // // Additions by lrt for tcia - // // attempt to reduce errors going through a Coyote Point // Equalizer load balance switch // httpClient.getParams().setParameter("http.socket.timeout", new // Integer(12000)); httpClient.getParams().setParameter("http.socket.timeout", new Integer(120000)); httpClient.getParams().setParameter("http.socket.receivebuffer", new Integer(16384)); httpClient.getParams().setParameter("http.tcp.nodelay", true); httpClient.getParams().setParameter("http.connection.stalecheck", false); // // end lrt additions HttpPost httpPostMethod = new HttpPost(url.toString()); List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>(); if (userId != null && passWd != null) { postParams.add(new BasicNameValuePair("userId", userId)); httpPostMethod.addHeader("password", passWd); } postParams.add(new BasicNameValuePair("numberOfSeries", Integer.toString(seriesList.size()))); int i = 0; for (String s : seriesList) { postParams.add(new BasicNameValuePair("series" + Integer.toString(++i), s)); } UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams); httpPostMethod.setEntity(query); HttpResponse response = httpClient.execute(httpPostMethod); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != HttpURLConnection.HTTP_OK) { returnStatus = responseCode; return null; } else { InputStream inputStream = response.getEntity().getContent(); data = IOUtils.readLines(inputStream); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (httpClient != null) { httpClient.getConnectionManager().shutdown(); } } return data; }
From source file:org.lightcouch.CouchDbClientBase.java
/** * @return {@link DefaultHttpClient} instance. *//*from w w w. j av a 2 s . c o m*/ private HttpClient createHttpClient(CouchDbProperties props) { DefaultHttpClient httpclient = null; try { SchemeSocketFactory ssf = null; if (props.getProtocol().equals("https")) { TrustManager trustManager = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] { trustManager }, null); ssf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SSLSocket socket = (SSLSocket) ssf.createSocket(null); socket.setEnabledCipherSuites(new String[] { "SSL_RSA_WITH_RC4_128_MD5" }); } else { ssf = PlainSocketFactory.getSocketFactory(); } SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme(props.getProtocol(), props.getPort(), ssf)); PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry); httpclient = new DefaultHttpClient(ccm); host = new HttpHost(props.getHost(), props.getPort(), props.getProtocol()); context = new BasicHttpContext(); // Http params httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, props.getSocketTimeout()); httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, props.getConnectionTimeout()); int maxConnections = props.getMaxConnections(); if (maxConnections != 0) { ccm.setMaxTotal(maxConnections); ccm.setDefaultMaxPerRoute(maxConnections); } if (props.getProxyHost() != null) { HttpHost proxy = new HttpHost(props.getProxyHost(), props.getProxyPort()); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } // basic authentication if (props.getUsername() != null && props.getPassword() != null) { httpclient.getCredentialsProvider().setCredentials(new AuthScope(props.getHost(), props.getPort()), new UsernamePasswordCredentials(props.getUsername(), props.getPassword())); props.clearPassword(); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(host, basicAuth); context.setAttribute(ClientContext.AUTH_CACHE, authCache); } // request interceptor httpclient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws IOException { if (log.isInfoEnabled()) log.info(">> " + request.getRequestLine()); } }); // response interceptor httpclient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws IOException { validate(response); if (log.isInfoEnabled()) log.info("<< Status: " + response.getStatusLine().getStatusCode()); } }); } catch (Exception e) { log.error("Error Creating HTTP client. " + e.getMessage()); throw new IllegalStateException(e); } return httpclient; }
From source file:no.kantega.kwashc.server.test.SSLCipherSuiteTest.java
private HttpResponse checkClientForCiphers(Site site, int httpsPort, HttpClient httpclient, String[] ciphers) throws NoSuchAlgorithmException, KeyManagementException, IOException { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] { allowAllTrustManager }, null); SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000); SSLSocket socket = (SSLSocket) sf.createSocket(params); socket.setEnabledCipherSuites(ciphers); URL url = new URL(site.getAddress()); InetSocketAddress address = new InetSocketAddress(url.getHost(), httpsPort); sf.connectSocket(socket, address, null, params); Scheme sch = new Scheme("https", httpsPort, sf); httpclient.getConnectionManager().getSchemeRegistry().register(sch); HttpGet request = new HttpGet( "https://" + url.getHost() + ":" + site.getSecureport() + url.getPath() + "blog"); return httpclient.execute(request); }
From source file:com.ah.be.common.PresenceUtil.java
public static HttpClient getHttpClientInstance(int maxConnections) { try {//w w w. j a v a2s. c o m SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new TrustManager[] { new ClientTrustManager() }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, ssf)); PoolingClientConnectionManager connMgr = new PoolingClientConnectionManager(schemeRegistry); connMgr.setMaxTotal(maxConnections); connMgr.setDefaultMaxPerRoute(maxConnections); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, SOCKET_TIMEOUT); HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT); HttpClient httpClient = new DefaultHttpClient(connMgr, params); return httpClient; } catch (Exception e) { log.error("getHttpClientInstance error.", e); return null; } }
From source file:io.restassured.config.SSLConfig.java
/** * Use relaxed HTTP validation. This means that you'll trust all hosts regardless if the SSL certificate is invalid. By using this * method you don't need to specify a keystore (see {@link #keyStore(String, String)} or trust store (see {@link #trustStore(java.security.KeyStore)}. * * @param protocol The standard name of the requested protocol. See the SSLContext section in the <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#SSLContext">Java Cryptography Architecture Standard Algorithm Name Documentation</a> for information about standard protocol names. * @return A new SSLConfig instance// w w w . j a v a2 s .co m */ public SSLConfig relaxedHTTPSValidation(String protocol) { AssertParameter.notNull(protocol, "Protocol"); SSLContext sslContext; try { sslContext = SSLContext.getInstance(protocol); } catch (NoSuchAlgorithmException e) { return SafeExceptionRethrower.safeRethrow(e); } // Set up a TrustManager that trusts everything try { sslContext.init(null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }, new SecureRandom()); } catch (KeyManagementException e) { return SafeExceptionRethrower.safeRethrow(e); } SSLSocketFactory sf = new SSLSocketFactory(sslContext, ALLOW_ALL_HOSTNAME_VERIFIER); return sslSocketFactory(sf); }
From source file:org.jets3t.service.utils.RestUtils.java
public static DefaultHttpClient wrapClient(HttpParams params) { try {//from ww w. j av a 2 s . c om SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override 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)); ClientConnectionManager ccm = new ConnManagerFactory().newInstance(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception ex) { ex.printStackTrace(); return null; } }
From source file:nl.esciencecenter.ptk.web.WebClient.java
protected void initHTTPS() throws CertificateStoreException { // Create SSL Socket factory with custom Certificate Store. // Default protocol is TLS (newer when SSL). // SSLContext sslContext = certStore.createSSLContext("SSLv3"); SSLContext sslContext = certStore.createSSLContext(SslConst.PROTOCOL_TLS); AbstractVerifier verifier;//from w ww .j a v a2 s . c o m if (config.sslOptions.disable_strict_hostname_checking) { verifier = new AllowAllHostnameVerifier(); } else { verifier = new StrictHostnameVerifier(); } // Create and register HTTPS socket factory SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, verifier); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", config.getPort(), socketFactory)); ClientConnectionManager manager = this.httpClient.getConnectionManager(); manager.getSchemeRegistry().register(new Scheme("https", config.getPort(), socketFactory)); }
From source file:net.yacy.cora.federate.solr.instance.RemoteInstance.java
/** * @return a custom scheme registry allowing https connections to servers using * a self-signed certificate// www . j ava2 s. com */ private static SchemeRegistry buildTrustSelfSignedSchemeRegistry() { /* Important note : use of deprecated Apache classes is required because SolrJ still use them internally (see HttpClientUtil). * Upgrade only when Solr implementation will become compatible */ SchemeRegistry registry = null; SSLContext sslContext; try { sslContext = SSLContextBuilder.create().loadTrustMaterial(TrustSelfSignedStrategy.INSTANCE).build(); registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); registry.register( new Scheme("https", 443, new SSLSocketFactory(sslContext, AllowAllHostnameVerifier.INSTANCE))); } catch (final Exception e) { // Should not happen ConcurrentLog.warn("RemoteInstance", "Error when initializing SSL context trusting self-signed certificates.", e); registry = null; } return registry; }
From source file:fr.eolya.utils.http.HttpLoader.java
/** * @param //from w ww . j av a2 s. c o m * @return */ private HttpClient getHttpClient(String url) { try { // ClientConnectionManager SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); registry.register(new Scheme("https", 443, sf)); ClientConnectionManager ccm = new PoolingClientConnectionManager(registry); // Params HttpParams httpParams = getHttpParams(); // DefaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(ccm, httpParams); // Proxy setProxy(httpClient, url, proxyHost, proxyPort, proxyExclude, proxyUserName, proxyPassword); // if (StringUtils.isNotEmpty(proxyHost)) { // if (StringUtils.isNotEmpty(proxyUserName) && StringUtils.isNotEmpty(proxyPassword)) { // httpClient.getCredentialsProvider().setCredentials( // new AuthScope(proxyHost,Integer.valueOf(proxyPort)), // new UsernamePasswordCredentials(proxyUserName, proxyPassword)); // } // HttpHost proxy = new HttpHost(proxyHost,Integer.valueOf(proxyPort)); // httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy); // } else { // httpClient.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY); // } // Cookies if (cookies != null) { CookieStore cookieStore = new BasicCookieStore(); Iterator<Entry<String, String>> it = cookies.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next(); BasicClientCookie cookie = new BasicClientCookie(pairs.getKey(), pairs.getValue()); //cookie.setDomain("your domain"); cookie.setPath("/"); cookieStore.addCookie(cookie); } httpClient.setCookieStore(cookieStore); } return new DecompressingHttpClient(httpClient); } catch (Exception e) { return new DecompressingHttpClient(new DefaultHttpClient()); } }