List of usage examples for javax.net.ssl SSLContext getSocketFactory
public final SSLSocketFactory getSocketFactory()
From source file:com.fujitsu.dc.test.utils.Http.java
static Socket createSocket(URL url) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException, KeyManagementException { String host = url.getHost();/* ww w . j a v a 2 s . c o m*/ int port = url.getPort(); String proto = url.getProtocol(); if (port < 0) { if ("https".equals(proto)) { port = PORT_HTTPS; } if ("http".equals(proto)) { port = PORT_HTTP; } } log.debug("sock: " + host + ":" + port); log.debug("proto: " + proto); // HTTPS?????????????SSLSocket??? if ("https".equals(proto)) { KeyManager[] km = null; TrustManager[] tm = { new javax.net.ssl.X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException { log.debug("Insecure SSLSocket Impl for Testing: NOP at X509TrustManager#checkClientTrusted"); } public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException { log.debug("Insecure SSLSocket Impl for Testing: NOP at X509TrustManager#checkServerTrusted"); } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } } }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(km, tm, new SecureRandom()); SocketFactory sf = sslContext.getSocketFactory(); return (SSLSocket) sf.createSocket(host, port); } // HTTPS???????? return new Socket(host, port); }
From source file:it_minds.dk.eindberetningmobil_android.server.DebugOkHttpStack.java
private static OkHttpClient getUnsafeOkHttpClient(OkHttpClient client) { try {/*from www .jav a 2 s. com*/ // Create a trust manager that does not validate certificate chains final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[] {}; } } }; // Install the all-trusting trust manager final SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // Create an ssl socket factory with our all-trusting manager final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); client.setSslSocketFactory(sslSocketFactory); client.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); return client; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.longtime.ajy.support.weixin.HttpsKit.java
/** * ??Post//from w w w. jav a 2 s.co m * * @param url * @param params * @return * @throws IOException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public static String post(String url, String params) {//throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { OutputStream out = null; InputStream in = null; HttpsURLConnection http = null; try { StringBuffer bufferRes = null; TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // SSLContextSSLSocketFactory SSLSocketFactory ssf = sslContext.getSocketFactory(); URL urlGet = new URL(url); http = (HttpsURLConnection) urlGet.openConnection(); // http.setConnectTimeout(TIME_OUT_CONNECT); // ? --?? http.setReadTimeout(TIME_OUT_READ); http.setRequestMethod("POST"); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setSSLSocketFactory(ssf); http.setDoOutput(true); http.setDoInput(true); http.connect(); out = http.getOutputStream(); out.write(params.getBytes("UTF-8")); out.flush(); in = http.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); String valueString = null; bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } return bufferRes.toString(); } catch (Exception e) { logger.error(String.format("HTTP POST url=[%s] param=[%s] due to fail.", url, params), e); } finally { if (null != out) { try { out.close(); } catch (IOException e) { logger.error(String.format("HTTP POST url=[%s] param=[%s] close outputstream due to fail.", url, params), e); } } if (null != in) { try { in.close(); } catch (IOException e) { logger.error(String.format("HTTP POST url=[%s] param=[%s] close inputstream due to fail.", url, params), e); } } if (http != null) { // http.disconnect(); } } return StringUtils.EMPTY; }
From source file:helpers.Methods.java
public static void trustAllCertificates() { //Certification check // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override/*from ww w . j a va 2 s .c o m*/ public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (GeneralSecurityException ex) { Variables.logger.Log(Methods.class, Variables.LogType.Error, "Error in trusting all certificates. Details:\r\n" + ex.getMessage()); } }
From source file:it.haefelinger.flaka.util.InitSSL.java
static public void install(TrustManager tm) throws Exception { // There's a problem (bug?) in Java 1.4 causing sc.init() to take a // very long time. Disabling installation of new trustmanager if // not 1.5 or newer. That's just fine cause 1.4 trustmanger accepts // self signed certificates. if (isjava15()) { SSLContext sc; sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[] { tm }, null); /* register with standard HTTP implementation */ HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); /* register with Jakarta HTTPClient */ Protocol https = new Protocol("https", new SSLSocketFactory(sc), 443); Protocol.registerProtocol("https", https); }/* w ww . j a va 2 s. com*/ }
From source file:com.photon.phresco.nativeapp.eshop.net.NetworkManager.java
public static boolean checkHttpsURLStatus(final String url) { boolean https_StatusFlag = false; System.out.println("Entered in checkHttpsURLStatus >>>>>>>>>>>>>>>"); URL httpsurl;//from ww w . ja v a 2s. c o m try { // Create a context that doesn't check certificates. SSLContext ssl_ctx = SSLContext.getInstance("TLS"); TrustManager[] trust_mgr = get_trust_mgr(); ssl_ctx.init(null, // key manager trust_mgr, // trust manager new SecureRandom()); // random number generator HttpsURLConnection.setDefaultSSLSocketFactory(ssl_ctx.getSocketFactory()); System.out.println("Url =========" + url); httpsurl = new URL(url); HttpsURLConnection con = (HttpsURLConnection) httpsurl.openConnection(); con.setHostnameVerifier(DO_NOT_VERIFY); int statusCode = con.getResponseCode(); System.out.println("statusCode =========" + statusCode); if (statusCode == HttpURLConnection.HTTP_OK) { https_StatusFlag = true; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } return https_StatusFlag; }
From source file:org.hyperic.plugin.vrealize.automation.VRAUtils.java
public static String getWGet(String path) { String retValue = null;//from w ww. ja v a2s. c o m try { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); URL url = new URL(path); URLConnection con; try { con = url.openConnection(); } catch (Exception e) { log.debug("Couldnt connect to vRa API"); return ""; } Reader reader = new InputStreamReader(con.getInputStream()); while (true) { int ch = reader.read(); if (ch == -1) { break; } retValue += (char) ch; } } catch (Exception e) { log.error(e.getMessage(), e); } return retValue; }
From source file:com.createtank.payments.coinbase.RequestClient.java
public static void disableCertificateValidation() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }// w w w. j a v a 2s. c om public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Ignore differences between given hostname and certificate hostname HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(hv); } catch (Exception e) { //Ignore } }
From source file:org.apache.maven.report.projectinfo.ProjectInfoReportUtils.java
/** * @param url not null/*from w w w .j a v a 2 s .c o m*/ * @param project not null * @param settings not null * @return the url connection with auth if required. Don't check the certificate if SSL scheme. * @throws IOException if any */ private static URLConnection getURLConnection(URL url, MavenProject project, Settings settings) throws IOException { URLConnection conn = url.openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); // conn authorization if (settings.getServers() != null && !settings.getServers().isEmpty() && project != null && project.getDistributionManagement() != null && (project.getDistributionManagement().getRepository() != null || project.getDistributionManagement().getSnapshotRepository() != null) && (StringUtils.isNotEmpty(project.getDistributionManagement().getRepository().getUrl()) || StringUtils.isNotEmpty( project.getDistributionManagement().getSnapshotRepository().getUrl()))) { Server server = null; if (url.toString().contains(project.getDistributionManagement().getRepository().getUrl())) { server = settings.getServer(project.getDistributionManagement().getRepository().getId()); } if (server == null && url.toString() .contains(project.getDistributionManagement().getSnapshotRepository().getUrl())) { server = settings.getServer(project.getDistributionManagement().getSnapshotRepository().getId()); } if (server != null && StringUtils.isNotEmpty(server.getUsername()) && StringUtils.isNotEmpty(server.getPassword())) { String up = server.getUsername().trim() + ":" + server.getPassword().trim(); String upEncoded = new String(Base64.encodeBase64Chunked(up.getBytes())).trim(); conn.setRequestProperty("Authorization", "Basic " + upEncoded); } } if (conn instanceof HttpsURLConnection) { HostnameVerifier hostnameverifier = new HostnameVerifier() { /** {@inheritDoc} */ public boolean verify(String urlHostName, SSLSession session) { return true; } }; ((HttpsURLConnection) conn).setHostnameVerifier(hostnameverifier); TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { /** {@inheritDoc} */ public void checkClientTrusted(final X509Certificate[] chain, final String authType) { } /** {@inheritDoc} */ public void checkServerTrusted(final X509Certificate[] chain, final String authType) { } /** {@inheritDoc} */ public X509Certificate[] getAcceptedIssuers() { return null; } } }; try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new SecureRandom()); SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory); } catch (NoSuchAlgorithmException e1) { // ignore } catch (KeyManagementException e) { // ignore } } return conn; }
From source file:com.camel.trainreserve.JDKHttpsClient.java
public static String doPost(String url, String cookieStr, String ctype, byte[] content, int connectTimeout, int readTimeout) throws Exception { HttpsURLConnection conn = null; OutputStream out = null;/*from ww w .j a va2 s . c om*/ String rsp = null; try { try { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); //SSLContext.setDefault(ctx); conn = getConnection(new URL(url), METHOD_POST, ctype); conn.setSSLSocketFactory(ctx.getSocketFactory()); conn.setRequestProperty("Cookie", cookieStr); conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); } catch (Exception e) { log.error("GET_CONNECTOIN_ERROR, URL = " + url, e); throw e; } try { out = conn.getOutputStream(); out.write(content); rsp = getResponseAsString(conn); } catch (IOException e) { log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e); throw e; } } finally { if (out != null) { out.close(); } if (conn != null) { conn.disconnect(); } } return rsp; }