Example usage for javax.net.ssl HttpsURLConnection setDefaultSSLSocketFactory

List of usage examples for javax.net.ssl HttpsURLConnection setDefaultSSLSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setDefaultSSLSocketFactory.

Prototype

public static void setDefaultSSLSocketFactory(SSLSocketFactory sf) 

Source Link

Document

Sets the default SSLSocketFactory inherited by new instances of this class.

Usage

From source file:com.addbean.autils.tools.OtherUtils.java

public static void trustAllHttpsURLConnection() {
    // Create a trust manager that does not validate certificate chains
    if (sslSocketFactory == null) {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override/*from  w  w w .  j av a  2 s .c o m*/
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, null);
            sslSocketFactory = sslContext.getSocketFactory();
        } catch (Throwable e) {
            Log.e("OtherUtils", e.getMessage());
        }
    }

    if (sslSocketFactory != null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        HttpsURLConnection.setDefaultHostnameVerifier(
                org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
}

From source file:net.tatans.rhea.network.view.OtherUtils.java

public static void trustAllHttpsURLConnection() {
    // Create a trust manager that does not validate certificate chains
    if (sslSocketFactory == null) {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override//ww  w.j ava  2  s . com
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, null);
            sslSocketFactory = sslContext.getSocketFactory();
        } catch (Throwable e) {
            TatansLogUtils.e(e.getMessage(), e);
        }
    }

    if (sslSocketFactory != null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        HttpsURLConnection.setDefaultHostnameVerifier(
                org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
}

From source file:edu.duke.cabig.c3pr.webservice.integration.C3PREmbeddedTomcatTestBase.java

/**
 * Code of this method was simply Googled.
 *//*from w w  w .ja  v  a  2s. com*/
void disableSSLVerification() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }

    com.sun.net.ssl.HostnameVerifier hv = new com.sun.net.ssl.HostnameVerifier() {

        public boolean verify(String urlHostname, String certHostname) {
            return true;
        }
    };
    com.sun.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(hv);

    HostnameVerifier hv2 = new HostnameVerifier() {

        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv2);

}

From source file:cn.isif.util_plus.util.OtherUtils.java

public static void trustAllHttpsURLConnection() {
    // Create a trust manager that does not validate certificate chains
    if (sslSocketFactory == null) {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override/*from ww  w .ja  v  a 2s . com*/
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, null);
            sslSocketFactory = sslContext.getSocketFactory();
        } catch (Throwable e) {
            LogUtils.e(e.getMessage(), e);
        }
    }

    if (sslSocketFactory != null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        HttpsURLConnection.setDefaultHostnameVerifier(
                org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
}

From source file:io.fabric8.apiman.gateway.ApimanGatewayStarter.java

private static URL waitForDependency(URL url, String serviceName, String key, String value, String username,
        String password) throws InterruptedException {
    boolean isFoundRunningService = false;
    ObjectMapper mapper = new ObjectMapper();
    int counter = 0;
    URL endpoint = null;//from   w  ww  . j av a  2  s. com
    while (!isFoundRunningService) {
        endpoint = resolveServiceEndpoint(url.getProtocol(), url.getHost(), String.valueOf(url.getPort()));
        if (endpoint != null) {
            String isLive = null;
            try {
                URL statusURL = new URL(endpoint.toExternalForm() + url.getPath());
                HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection();
                urlConnection.setConnectTimeout(500);
                if (urlConnection instanceof HttpsURLConnection) {
                    try {
                        KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(TRUSTSTORE_PATH,
                                TRUSTSTORE_PASSWORD_PATH);
                        TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo);
                        KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info(CLIENT_KEYSTORE_PATH,
                                CLIENT_KEYSTORE_PASSWORD_PATH);
                        KeyManager[] kms = KeyStoreUtil.getKeyManagers(kPathInfo);
                        final SSLContext sc = SSLContext.getInstance("TLS");
                        sc.init(kms, tms, new java.security.SecureRandom());
                        final SSLSocketFactory socketFactory = sc.getSocketFactory();
                        HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
                        HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
                        httpsConnection.setHostnameVerifier(new DefaultHostnameVerifier());
                        httpsConnection.setSSLSocketFactory(socketFactory);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        throw e;
                    }
                }
                if (Utils.isNotNullOrEmpty(username)) {
                    String encoded = Base64.getEncoder()
                            .encodeToString((username + ":" + password).getBytes("UTF-8"));
                    log.info(username + ":******");
                    urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
                }
                isLive = IOUtils.toString(urlConnection.getInputStream());
                Map<String, Object> esResponse = mapper.readValue(isLive,
                        new TypeReference<Map<String, Object>>() {
                        });
                if (esResponse.containsKey(key) && value.equals(String.valueOf(esResponse.get(key)))) {
                    isFoundRunningService = true;
                } else {
                    if (counter % 10 == 0)
                        log.info(endpoint.toExternalForm() + " not yet up (host=" + endpoint.getHost() + ")"
                                + isLive);
                }
            } catch (Exception e) {
                if (counter % 10 == 0)
                    log.info(endpoint.toExternalForm() + " not yet up. (host=" + endpoint.getHost() + ")"
                            + e.getMessage());
            }
        } else {
            if (counter % 10 == 0)
                log.info("Could not find " + serviceName + " in namespace, waiting..");
        }
        counter++;
        Thread.sleep(1000l);
    }
    return endpoint;
}

From source file:eu.siacs.conversations.ui.ServiceBrowserFragment.java

public static boolean exists(String URLName) {

    X509TrustManager trustManager = new X509TrustManager() {

        @Override/* w w w . j ava 2 s .  c  o m*/
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // NOTE : This is where we can calculate the certificate's fingerprint,
            // show it to the user and throw an exception in case he doesn't like it
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    };

    // Create a trust manager that does not validate certificate chains
    X509TrustManager[] trustAllCerts = new X509TrustManager[] { trustManager };

    // Install the all-trusting trust manager
    SSLSocketFactory noSSLv3Factory = null;
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            noSSLv3Factory = new TLSSocketFactory(trustAllCerts, new SecureRandom());
        } else {
            noSSLv3Factory = sc.getSocketFactory();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(noSSLv3Factory);
    } catch (GeneralSecurityException e) {
    }

    try {
        HttpsURLConnection.setFollowRedirects(false);
        // note : you may also need
        //        HttpURLConnection.setInstanceFollowRedirects(false)
        URL url = new URL(URLName);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setSSLSocketFactory(noSSLv3Factory);
        con.setRequestProperty("Accept-Encoding", "");
        //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
        con.setHostnameVerifier(new NullHostNameVerifier(url.getHost()));
        con.setRequestMethod("HEAD");
        return (con.getResponseCode() == HttpsURLConnection.HTTP_OK);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:com.mytwitter.Network.NetworkHelper.java

/**
 * Create a trust manager that does not validate SSL certificate chains.
 *///from   www  . j a v a2  s  .c  o  m
public void trustAllHosts() {

    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    } };

    // Install the all-trusting trust manager
    try {
        // Backup the current SSL socket factory
        defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
        // Install our all trusting manager
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.flink.runtime.rest.RestServerEndpointITCase.java

@Before
public void setup() throws Exception {
    config.setString(WebOptions.UPLOAD_DIR, temporaryFolder.newFolder().getCanonicalPath());

    defaultSSLContext = SSLContext.getDefault();
    defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    final SSLContext sslClientContext = SSLUtils.createRestClientSSLContext(config);
    if (sslClientContext != null) {
        SSLContext.setDefault(sslClientContext);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslClientContext.getSocketFactory());
    }/* ww w.j  ava  2s. co m*/

    RestServerEndpointConfiguration serverConfig = RestServerEndpointConfiguration.fromConfiguration(config);
    RestClientConfiguration clientConfig = RestClientConfiguration.fromConfiguration(config);

    final String restAddress = "http://localhost:1234";
    RestfulGateway mockRestfulGateway = mock(RestfulGateway.class);
    when(mockRestfulGateway.requestRestAddress(any(Time.class)))
            .thenReturn(CompletableFuture.completedFuture(restAddress));

    final GatewayRetriever<RestfulGateway> mockGatewayRetriever = () -> CompletableFuture
            .completedFuture(mockRestfulGateway);

    testHandler = new TestHandler(CompletableFuture.completedFuture(restAddress), mockGatewayRetriever,
            RpcUtils.INF_TIMEOUT);

    TestVersionHandler testVersionHandler = new TestVersionHandler(
            CompletableFuture.completedFuture(restAddress), mockGatewayRetriever, RpcUtils.INF_TIMEOUT);

    TestVersionSelectionHandler1 testVersionSelectionHandler1 = new TestVersionSelectionHandler1(
            CompletableFuture.completedFuture(restAddress), mockGatewayRetriever, RpcUtils.INF_TIMEOUT);

    TestVersionSelectionHandler2 testVersionSelectionHandler2 = new TestVersionSelectionHandler2(
            CompletableFuture.completedFuture(restAddress), mockGatewayRetriever, RpcUtils.INF_TIMEOUT);

    testUploadHandler = new TestUploadHandler(CompletableFuture.completedFuture(restAddress),
            mockGatewayRetriever, RpcUtils.INF_TIMEOUT);

    final StaticFileServerHandler<RestfulGateway> staticFileServerHandler = new StaticFileServerHandler<>(
            mockGatewayRetriever, CompletableFuture.completedFuture(restAddress), RpcUtils.INF_TIMEOUT,
            temporaryFolder.getRoot());

    final List<Tuple2<RestHandlerSpecification, ChannelInboundHandler>> handlers = Arrays.asList(
            Tuple2.of(new TestHeaders(), testHandler), Tuple2.of(TestUploadHeaders.INSTANCE, testUploadHandler),
            Tuple2.of(testVersionHandler.getMessageHeaders(), testVersionHandler),
            Tuple2.of(testVersionSelectionHandler1.getMessageHeaders(), testVersionSelectionHandler1),
            Tuple2.of(testVersionSelectionHandler2.getMessageHeaders(), testVersionSelectionHandler2),
            Tuple2.of(WebContentHandlerSpecification.getInstance(), staticFileServerHandler));

    serverEndpoint = new TestRestServerEndpoint(serverConfig, handlers);
    restClient = new TestRestClient(clientConfig);

    serverEndpoint.start();
    serverAddress = serverEndpoint.getServerAddress();
}

From source file:org.apache.chemistry.shell.Main.java

private static void acceptSelfSignedCertificates() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }/* w w w  . j  a va 2 s.co m*/

        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }

        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java

/**
 * WARNING : only use in development environment,
 * DO NOT USE in production or commercial environments !!!
 * Trust every server - do not check for any certificate
 *//* w ww.j a v a2s  .  c  o m*/
private static void trustAllHosts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                throws CertificateException {

        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                throws CertificateException {

        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

    } };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
}