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:cn.ctyun.amazonaws.http.AmazonHttpClient.java
/** * Disables the default strict hostname verification in this client and * instead uses a browser compatible hostname verification strategy (i.e. * cert hostname wildcards are evaulated more liberally). *///from www . j a v a 2s . c o m public void disableStrictHostnameVerification() { /* * If SSL cert checking for endpoints is disabled, we don't need * to do any changes to the SSL context. */ if (System.getProperty("com.amazonaws.sdk.disableCertChecking") != null) { return; } try { SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry(); SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(), SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); Scheme https = new Scheme("https", 443, sf); schemeRegistry.register(https); } catch (NoSuchAlgorithmException e) { throw new AmazonClientException( "Unable to access default SSL context to disable strict hostname verification"); } }
From source file:com.unboundid.scim.sdk.examples.ClientExample.java
/** * Create an SSL-enabled Wink client config from the provided information. * The returned client config may be used to create a SCIM service object. * IMPORTANT: This should not be used in production because no validation * is performed on the server certificate returned by the SCIM service. * * @param userName The HTTP Basic Auth user name. * @param password The HTTP Basic Auth password. * * @return An Apache Wink client config. *//*from www .j a v a2s . c o m*/ public static ClientConfig createHttpBasicClientConfig(final String userName, final String password) { SSLSocketFactory sslSocketFactory; try { final SSLContext sslContext = SSLContext.getInstance("TLS"); // Do not use these settings in production. sslContext.init(null, new TrustManager[] { new BlindTrustManager() }, new SecureRandom()); sslSocketFactory = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (KeyManagementException e) { throw new RuntimeException(e.getLocalizedMessage()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.getLocalizedMessage()); } final HttpParams params = new BasicHttpParams(); DefaultHttpClient.setDefaultHttpParams(params); params.setBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, true); params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true); final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, sslSocketFactory)); final PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(schemeRegistry); mgr.setMaxTotal(200); mgr.setDefaultMaxPerRoute(20); final DefaultHttpClient httpClient = new DefaultHttpClient(mgr, params); final Credentials credentials = new UsernamePasswordCredentials(userName, password); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0); ClientConfig clientConfig = new ApacheHttpClientConfig(httpClient); clientConfig.setBypassHostnameVerification(true); return clientConfig; }
From source file:org.ancoron.osgi.test.glassfish.GlassfishDerbyTest.java
protected DefaultHttpClient getHTTPClient() throws NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new X509TrustManager() { @Override/*from w w w . ja va 2 s .c o m*/ public X509Certificate[] getAcceptedIssuers() { System.out.println("getAcceptedIssuers ============="); return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { System.out.println("checkClientTrusted ============="); } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { System.out.println("checkServerTrusted ============="); } } }, new SecureRandom()); SSLSocketFactory sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme httpsScheme = new Scheme("https", 8181, sf); PlainSocketFactory plain = new PlainSocketFactory(); Scheme httpScheme = new Scheme("http", 8080, plain); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); schemeRegistry.register(httpScheme); HttpParams params = new BasicHttpParams(); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry); // Increase max total connection to 200 cm.setMaxTotal(200); // Increase default max connection per route to 20 cm.setDefaultMaxPerRoute(20); DefaultHttpClient httpClient = new DefaultHttpClient(cm, params); httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); return httpClient; }
From source file:eu.cassandra.training.utils.APIUtilities.java
/** * This function is used to send the user's credentials to the Cassandra * Server.// w ww. j a v a2 s. c om * * @param username * The username of the user in the server. * @param password * The password of the user in the server. * @return true if connected, else false. * @throws Exception */ public static boolean sendUserCredentials(String username, char[] password) throws Exception { String pass = String.valueOf(password); try { UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, pass); char SEP = File.separatorChar; File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); File file = new File(dir, "jssecacerts"); if (file.isFile() == false) { InstallCert.createCertificate("160.40.50.233", 8443); JFrame success = new JFrame(); JOptionPane.showMessageDialog(success, "Certificate was created for user " + username + ". Now the connection will start", "Response Model Exported", JOptionPane.INFORMATION_MESSAGE); } try { sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, null, null); sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (Exception e1) { } Scheme scheme = new Scheme("https", 8443, sf); httpclient.getConnectionManager().getSchemeRegistry().register(scheme); HttpGet httpget = new HttpGet(url + "/usr"); httpget.addHeader(new BasicScheme().authenticate(usernamePasswordCredentials, httpget, localcontext)); System.out.println("executing request: " + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget, localcontext); HttpEntity entity = response.getEntity(); String responseString = EntityUtils.toString(entity, "UTF-8"); System.out.println(responseString); DBObject dbo = (DBObject) JSON.parse(responseString); if (dbo.get("success").toString().equalsIgnoreCase("true")) { BasicDBList dataObj = (BasicDBList) dbo.get("data"); DBObject dbo2 = (DBObject) dataObj.get(0); userID = dbo2.get("usr_id").toString(); System.out.println("userId: " + userID); return true; } else { System.out.println(false); return false; } } finally { } }
From source file:com.predic8.membrane.test.AssertUtils.java
public static void trustAnyHTTPSServer(int port) throws NoSuchAlgorithmException, KeyManagementException { SSLContext context = SSLContext.getInstance("SSL"); context.init(null, new TrustManager[] { new X509TrustManager() { @Override//w ww. j a va 2 s . c om public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } } }, new SecureRandom()); SSLSocketFactory sslsf = new SSLSocketFactory(context, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme scheme = new Scheme("https", port, sslsf); if (hc == null) hc = new DefaultHttpClient(); hc.getConnectionManager().getSchemeRegistry().register(scheme); }
From source file:com.dumiduh.das.AnalyticsAPIInvoker.java
private String invoke(String url, String username, String pwd, String type) { TrustStrategyExt strategy = new TrustStrategyExt(); String jsonString = ""; try {// w ww . j av a 2 s . c om SSLSocketFactory sf = new SSLSocketFactory(strategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("https", Integer.parseInt(port), sf)); ClientConnectionManager ccm = new PoolingClientConnectionManager(registry); DefaultHttpClient client = new DefaultHttpClient(ccm); HttpGet get = new HttpGet(url); String header = "Basic " + getBase64EncodedToken(username, pwd); get.setHeader("Authorization", header); HttpResponse resp = client.execute(get); if (type.equals("body")) { BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } jsonString = result.toString(); } else if (type.equals("header")) { StringBuffer result = new StringBuffer(); Header[] headers = resp.getAllHeaders(); for (Header h : headers) { result.append(h.getName() + " : " + h.getValue()); } result.append("status code : " + resp.getStatusLine().getStatusCode()); jsonString = result.toString(); } client.close(); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyManagementException ex) { Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex); } catch (KeyStoreException ex) { Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex); } catch (UnrecoverableKeyException ex) { Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex); } catch (NumberFormatException ex) { Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex); } return jsonString; }
From source file:org.esxx.js.protocol.HTTPHandler.java
private static synchronized ClientConnectionManager getConnectionManager() { if (connectionManager == null) { SchemeRegistry sr = new SchemeRegistry(); sr.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // sr.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); try {/*from ww w . ja va 2 s. c om*/ SSLContext sslcontext = SSLContext.getInstance(SSLSocketFactory.TLS); sslcontext.init(null, new TrustManager[] { new X509TrustManager() { @Override public void checkServerTrusted(X509Certificate[] chain, String auth) { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @Override public void checkClientTrusted(X509Certificate[] certs, String auth) { } } }, new java.security.SecureRandom()); SSLSocketFactory ssf = new SSLSocketFactory(sslcontext, null); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); sr.register(new Scheme("https", ssf, 443)); } catch (Exception ex) { ex.printStackTrace(); } connectionManager = new ThreadSafeClientConnManager(getHttpParams(), sr); } return connectionManager; }
From source file:wsattacker.plugin.dos.dosExtension.requestSender.RequestSenderImpl.java
private String sendRequestHttpClient(RequestObject requestObject) { // get Post Request HttpPost post = this.createHttpPostMethod(requestObject); // set afterReceive to default value to handle missing responses afterReceive = 0;/*from w w w. ja v a 2s.c o m*/ // Get HTTP client and execute request try { URL url = new URL(requestObject.getEndpoint()); String protocol = url.getProtocol(); HttpClient httpClient; if (protocol.equalsIgnoreCase("https")) { SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory sf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme httpsScheme = new Scheme("https", url.getPort(), sf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); // apache HttpClient version >4.2 should use // BasicClientConnectionManager ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry); httpClient = new DefaultHttpClient(cm); } else { httpClient = new DefaultHttpClient(); } httpClient.getParams().setParameter("http.socket.timeout", TIMEOUT); httpClient.getParams().setParameter("http.connection.timeout", TIMEOUT); httpClient.getParams().setParameter("http.connection-manager.max-per-host", TIMEOUT); httpClient.getParams().setParameter("http.connection-manager.max-total", new Integer(3000)); // > params.setDefaultMaxConnectionsPerHost(3000); // > params.setMaxTotalConnections(3000); beforeSend = System.nanoTime(); HttpResponse response = httpClient.execute(post); StringWriter writer = new StringWriter(); IOUtils.copy(response.getEntity().getContent(), writer, "UTF-8"); responseString = writer.toString(); afterReceive = System.nanoTime(); // System.out.println("Response status code: " + result); // System.out.println("Response body: " + responseString); } catch (IOException ex) { // Logger.getLogger(RequestSender.class.getName()).log(Level.SEVERE, // null, ex); System.out.println("--RequestSender - IO Exception: " + ex.getMessage()); // ex.printStackTrace(); } catch (Exception e) { // Request timed out!? System.out.println("--RequestSender - unexpected Exception: " + e.getMessage()); } finally { // Release current connection to the connection pool // post.releaseConnection(); if (responseString == null) { responseString = ""; } // Set afterReceive to beforeSend if afterReceive is 0 so that there // is no huge negative response time when the web service doesn't answer if (afterReceive == 0) { afterReceive = beforeSend; } } return responseString; }
From source file:org.envirocar.analyse.AggregationAlgorithm.java
protected HttpClient createClient() throws IOException, KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException { DefaultHttpClient result = new DefaultHttpClient(); SchemeRegistry sr = result.getConnectionManager().getSchemeRegistry(); SSLSocketFactory sslsf = new SSLSocketFactory(new TrustStrategy() { @Override/* www .j a v a 2 s . c o m*/ public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }, new AllowAllHostnameVerifier()); Scheme httpsScheme2 = new Scheme("https", 443, sslsf); sr.register(httpsScheme2); return result; }
From source file:org.sonatype.nexus.client.rest.jersey.NexusClientFactoryImpl.java
protected ApacheHttpClient4 doCreateHttpClientFor(final ConnectionInfo connectionInfo, final XStream xstream) { final ApacheHttpClient4Config config = new DefaultApacheHttpClient4Config(); config.getSingletons().add(new XStreamXmlProvider(xstream, APPLICATION_XML_UTF8_TYPE)); // set _real_ URL for baseUrl, and not a redirection (typically http instead of https) config.getProperties().put(PROPERTY_FOLLOW_REDIRECTS, Boolean.FALSE); applyAuthenticationIfAny(connectionInfo, config); applyProxyIfAny(connectionInfo, config); // obey JSSE defined system properties config.getProperties().put(ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER, new PoolingClientConnectionManager(SchemeRegistryFactory.createSystemDefault())); final ApacheHttpClient4 client = ApacheHttpClient4.create(config); // set UA//from w w w .j av a 2s . c o m client.getClientHandler().getHttpClient().getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Nexus-Client/" + discoverClientVersion()); // "tweak" HTTPS scheme as requested final TrustStrategy trustStrategy; switch (connectionInfo.getSslCertificateValidation()) { case NONE: trustStrategy = new TrustStrategy() { @Override public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { return true; } }; break; case LAX: trustStrategy = new TrustSelfSignedStrategy(); break; default: trustStrategy = null; } final X509HostnameVerifier hostnameVerifier; switch (connectionInfo.getSslCertificateHostnameValidation()) { case NONE: hostnameVerifier = new AllowAllHostnameVerifier(); break; case STRICT: hostnameVerifier = new StrictHostnameVerifier(); break; default: hostnameVerifier = new BrowserCompatHostnameVerifier(); } try { final SSLSocketFactory ssf = new SSLSocketFactory(trustStrategy, hostnameVerifier); final Scheme tweakedHttpsScheme = new Scheme("https", 443, ssf); client.getClientHandler().getHttpClient().getConnectionManager().getSchemeRegistry() .register(tweakedHttpsScheme); } catch (Exception e) { Throwables.propagate(e); } // NXCM-4547 JERSEY-1293 Enforce proxy setting on httpclient enforceProxyUri(config, client); if (LOG.isDebugEnabled()) { client.addFilter(new LoggingFilter()); } client.addFilter(new RequestFilters()); return client; }