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:be.fedict.eid.idp.sp.protocol.openid.OpenIDSSLSocketFactory.java

/**
 * Installs the OpenID SSL Socket Factory. Trusts all server certificates.
 * For testing purposes only!//from www .  j a v a2s .co  m
 * 
 * @throws NoSuchAlgorithmException
 *             could not get an SSLContext instance
 * @throws KeyManagementException
 *             failed to initialize the SSLContext
 */
public static void installAllTrusted() throws KeyManagementException, NoSuchAlgorithmException {
    SSLSocketFactory sslSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    if (!(sslSocketFactory instanceof OpenIDSSLSocketFactory)) {
        LOG.debug("installing OpenID SSL Socket Factory...");
        OpenIDSSLSocketFactory openIDSSLSocketFactory = new OpenIDSSLSocketFactory();
        HttpsURLConnection.setDefaultSSLSocketFactory(openIDSSLSocketFactory);
        System.setProperty("java.protocol.handler.pkgs", "javax.net.ssl");
        HttpsURLConnection.setDefaultHostnameVerifier(
                org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } else {
        LOG.debug("OpenID SSL Socket Factory already installed.");
    }
}

From source file:com.gmobi.poponews.util.HttpHelper.java

static void disableSslCheck() {
    if (initialized)
        return;//  www  . ja  v a  2s  .c  o  m
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    SSLContext sc;
    try {
        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);
        initialized = true;
    } catch (Exception e) {
        Logger.error(e);
    }

}

From source file:com.sitewhere.groovy.device.communication.rest.RestHelper.java

/**
 * Create SSL context that allows bad certificates.
 * //from  w ww  .  j  av a2 s . c om
 * @return
 */
protected SSLContext createContext() {
    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, null);
        SSLContext.setDefault(sc);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return sc;

    } catch (Exception e) {
    }
    return null;
}

From source file:mendhak.teamcity.stash.api.StashClient.java

private HttpURLConnection GetConnection(String targetURL)
        throws IOException, NoSuchAlgorithmException, KeyManagementException {
    URL url = new URL(targetURL);
    if (targetURL.startsWith("http://")) {
        return (HttpURLConnection) url.openConnection();
    }/*from  w  ww  . j a va2s.c  om*/

    //Create an all trusting SSL URL Connection
    //For in-house Stash servers with self-signed certs

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public 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);

    return (HttpsURLConnection) url.openConnection();

}

From source file:org.openadaptor.util.PropertiesPoster.java

/**
 * Utility method which will attempt to POST the supplied properties information to the supplied URL.
 * //from w w w  . ja  va  2  s.c o  m
 * This method currently contains an all trusting trust manager for use with https. This will be replaced with a more
 * secure trust manager which will use a cert store.
 * 
 * @param registrationURL
 * @param properties
 * @throws Exception
 */
protected static void syncPostHttp(String registrationURL, Properties properties) throws Exception {

    URL url = new URL(registrationURL);
    String postData = generatePOSTData(properties);
    log.debug("Protocol: " + url.getProtocol());
    if (url.getProtocol().equals("https")) {

        // https connection

        // TODO: Replace this all trusting manager with one that uses a cert store
        // Create a trust manager that does not validate certificate chains
        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) {
            }
        } };

        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());

        HttpsURLConnection secureConnection = null;
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        secureConnection = (HttpsURLConnection) url.openConnection();
        secureConnection.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(secureConnection.getOutputStream());
        writer.write(postData);
        writer.flush();
        int responseCode = secureConnection.getResponseCode();
        if (HttpsURLConnection.HTTP_OK != responseCode) {
            log.error("\nFailed to register. Response Code " + responseCode + "\nResponse message:"
                    + secureConnection.getResponseMessage() + "\nRegistration URL: " + registrationURL
                    + "\nData: " + generateString(properties));
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(secureConnection.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            log.debug("Returned data: " + line);
        }
        writer.close();
        br.close();
    } else {

        // Normal http connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(postData);
        writer.flush();
        int responseCode = connection.getResponseCode();
        if (HttpURLConnection.HTTP_OK != responseCode) {
            log.error("\nFailed to register. Response Code " + responseCode + "\nResponse message:"
                    + connection.getResponseMessage() + "\nRegistration URL: " + registrationURL + "\nData: "
                    + generateString(properties));
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            log.debug("Returned data: " + line);
        }
        writer.close();
        br.close();
    }
}

From source file:com.phonegap.FileTransfer.java

/**
 * This function will install a trust manager that will blindly trust all SSL 
 * certificates.  The reason this code is being added is to enable developers 
 * to do development using self signed SSL certificates on their web server.
 * /* w  w  w.j  a  v a 2 s . c o  m*/
 * The standard HttpsURLConnection class will throw an exception on self 
 * signed certificates if this code is not run.
 */
private void trustAllHosts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.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) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
}

From source file:net.Downloader.java

public void run() {
    OutputStream os = null;//from   www.  ja v  a  2 s  . c  o m
    InputStream is = null;

    ProgressListener progressListener = new ProgressListener();
    try {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new SSLManager() };

        // Install the all-trusting trust manager
        final 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);

        os = new FileOutputStream(fl);
        is = conn.getInputStream();

        CountingStream dcount = new CountingStream(os);
        dcount.setListener(progressListener);

        status = "Downloading";
        // begin transfer by writing to dcount, not os.
        IOUtils.copy(is, dcount);

    } catch (UnknownHostException u) {
        System.err.println("Uknown Host2");
        u.printStackTrace();
    } catch (Exception e) {
        System.out.println(e);
    } finally {
        try {
            status = "Finished";
            if (os != null) {
                os.close();
            }
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.eclipse.dirigible.ide.common.io.ProxyUtils.java

private static void setTrustAllSSL() throws IOException {
    try {/*from  w  w  w . j  a va  2  s.  c  om*/
        HttpsURLConnection.setDefaultSSLSocketFactory(createTrustAllSSLContext().getSocketFactory());
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } catch (KeyManagementException e) {
        throw new IOException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    }
}

From source file:edu.indiana.d2i.registryext.RegistryExtAgent.java

private boolean disableSSL() {
    // Create empty HostnameVerifier
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }/*from www. ja va2 s .  c om*/
    };

    // Create a trust manager that does not validate certificate chains
    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) {
        }
    } };

    // install all-trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory sslSocketFactory = sc.getSocketFactory();
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
        return true;
    } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e);
        return false;
    } catch (KeyManagementException e) {
        logger.error(e.getMessage(), e);
        return false;
    }
}

From source file:org.wso2.carbon.dashboard.migratetool.DSPortalAppMigrationTool.java

public String invokeRestAPI(String requestURL, String requestType, String sessionId) {
    try {/*from  w ww  . j av a 2  s  . co m*/
        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());

        URL url = new URL(requestURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(requestType);
        if (sessionId != null) {
            conn.setRequestProperty("Cookie", "JSESSIONID=" + sessionId);
        }
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        String output;
        StringBuilder buffer = new StringBuilder();
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
            buffer.append(output);
        }
        output = buffer.toString();
        conn.disconnect();
        return output;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {

    } catch (NoSuchAlgorithmException e) {

    }
    return null;
}