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:org.openadaptor.util.hosting.HostedConnection.java

protected HostedConnection() {
    log.debug("Installing all-trusting Security manager");

    SSLContext sc;//w w w.ja v  a2s  .  c  o  m
    try {
        sc = SSLContext.getInstance("SSL");
        sc.init(null, trustManagers, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        new URL("https://not.real");
    } catch (NoSuchAlgorithmException e) {
        fail("Failed to establish SSL context", e);

    } catch (KeyManagementException e) {
        fail(e.getMessage(), e);

    } catch (MalformedURLException e) {
        fail("Failed to setup security manager " + e);
    }
}

From source file:cyrille.net.ssl.AcceptAllSSLSocketFactoryConfigurator.java

@Override
public void afterPropertiesSet() throws Exception {
    if (enabled) {
        System.err.println("WARNING : DISABLE ALL SSL VERIFICATIONS " + this.getClass());
        HttpsURLConnection.setDefaultSSLSocketFactory(new AcceptAllSSLSocketFactory());
    }//from   w w  w.j  ava  2 s  .c  o  m
}

From source file:org.vsearchd.crawler.backend.BackendSessionHTTPS.java

private Scheme getHttpSslTheme(String url) throws Exception {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, getTrustManager(), null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    SSLSocketFactory socketFactory = new SSLSocketFactory(sc, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return new Scheme("https", Integer.valueOf(this.getBackendServer().getPort()), socketFactory);
}

From source file:com.ibm.caas.CaaSResource.java

/**
 * Pass throughout CERTs [workaround]/*from w w  w .  j a  v a2s . com*/
 */
public void relaxHostChecking() {

    // Override SSL Trust manager without certificate chains validation
    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) {
        }

    } };

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

        // Hostname verification. 
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            /**
             * Verify that the host name is an acceptable match with the server's authentication scheme.
             * @hostname - the host name
             * @session - SSLSession used on the connection to host
             * @return true if the host name is acceptable
             */
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        // Sets the default HostnameVerifier by all-trusting host verifier.
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.appspot.apprtc.util.AsyncHttpURLConnection.java

private void sendHttpMessage() {
    if (mIsBitmap) {
        Bitmap bitmap = ThumbnailsCacheManager.getBitmapFromDiskCache(url);

        if (bitmap != null) {
            events.onHttpComplete(bitmap);
            return;
        }//from   ww w  .j  a v  a  2s .  com
    }

    X509TrustManager trustManager = new X509TrustManager() {

        @Override
        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 {
        }
    };

    //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
    // 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) {
    }

    HttpsURLConnection connection = null;
    try {
        URL urlObj = new URL(url);
        connection = (HttpsURLConnection) urlObj.openConnection();
        connection.setSSLSocketFactory(noSSLv3Factory);

        HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier(urlObj.getHost()));
        connection.setHostnameVerifier(new NullHostNameVerifier(urlObj.getHost()));
        byte[] postData = new byte[0];
        if (message != null) {
            postData = message.getBytes("UTF-8");
        }

        if (msCookieManager.getCookieStore().getCookies().size() > 0) {
            // While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';'
            connection.setRequestProperty("Cookie",
                    TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
        }

        /*if (method.equals("PATCH")) {
          connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
          connection.setRequestMethod("POST");
        }
        else {*/
        connection.setRequestMethod(method);
        //}

        if (authorization.length() != 0) {
            connection.setRequestProperty("Authorization", authorization);
        }
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setConnectTimeout(HTTP_TIMEOUT_MS);
        connection.setReadTimeout(HTTP_TIMEOUT_MS);
        // TODO(glaznev) - query request origin from pref_room_server_url_key preferences.
        //connection.addRequestProperty("origin", HTTP_ORIGIN);
        boolean doOutput = false;
        if (method.equals("POST") || method.equals("PATCH")) {
            doOutput = true;
            connection.setDoOutput(true);
            connection.setFixedLengthStreamingMode(postData.length);
        }
        if (contentType == null) {
            connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
        } else {
            connection.setRequestProperty("Content-Type", contentType);
        }

        // Send POST request.
        if (doOutput && postData.length > 0) {
            OutputStream outStream = connection.getOutputStream();
            outStream.write(postData);
            outStream.close();
        }

        // Get response.
        int responseCode = 200;
        try {
            connection.getResponseCode();
        } catch (IOException e) {

        }
        getCookies(connection);
        InputStream responseStream;

        if (responseCode > 400) {
            responseStream = connection.getErrorStream();
        } else {
            responseStream = connection.getInputStream();
        }

        String responseType = connection.getContentType();
        if (responseType.startsWith("image/")) {
            Bitmap bitmap = BitmapFactory.decodeStream(responseStream);
            if (mIsBitmap && bitmap != null) {
                ThumbnailsCacheManager.addBitmapToCache(url, bitmap);
            }
            events.onHttpComplete(bitmap);
        } else {
            String response = drainStream(responseStream);
            events.onHttpComplete(response);
        }
        responseStream.close();
        connection.disconnect();
    } catch (SocketTimeoutException e) {
        events.onHttpError("HTTP " + method + " to " + url + " timeout");
    } catch (IOException e) {
        if (connection != null) {
            connection.disconnect();
        }
        events.onHttpError("HTTP " + method + " to " + url + " error: " + e.getMessage());
    } catch (ClassCastException e) {
        e.printStackTrace();
    }
}

From source file:com.ds.kaixin.Kaixin.java

private Kaixin() {
    System.setProperty("http.keepAlive", "false");

    SSLContext sslContext = null;

    try {//from  w  w w.j  a  v  a2 s .com
        sslContext = SSLContext.getInstance("TLS");
        X509TrustManager[] xtmArray = new X509TrustManager[] { xtm };
        sslContext.init(null, xtmArray, new java.security.SecureRandom());
    } catch (GeneralSecurityException gse) {
    }
    if (sslContext != null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    }

    HttpsURLConnection.setDefaultHostnameVerifier(hnv);
}

From source file:org.socialbiz.cog.util.SSLPatch.java

/**
* a call to disableSSLCertValidation will disable certificate validation
* for SSL connection made after this call.   This is installed as the
* default in the JVM for future calls.//from  w w  w  . j a  va  2s.co m
*
* Returns the properly initialized SSLContext in case it is needed for
* something else (like Apache HttpClient libraries) but if you don't need
* it you can ignore it.
*/
public static SSLContext disableSSLCertValidation() throws Exception {

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

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

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(getAllHostVerifier());

    return sc;
}

From source file:test.integ.be.e_contract.sts.CXFSTSClientTest.java

@Before
public void setUp() throws Exception {
    TrustManager trustManager = new MyTrustManager();
    TrustManager[] sslTrustManagers = new TrustManager[] { trustManager };
    SSLContext ssl_ctx = SSLContext.getInstance("TLS");
    ssl_ctx.init(null, sslTrustManagers, new SecureRandom());
    SSLSocketFactory sslSocketFactory = ssl_ctx.getSocketFactory();
    HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);

    HostnameVerifier hostnameVerifier = new MyHostnameVerifier();
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    Security.addProvider(new BeIDProvider());
}

From source file:org.apache.hadoop.io.crypto.bee.RestClient.java

private InputStream httpsIgnoreCertificate(final URL url) throws IOException {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }//  ww w.  jav  a  2 s. c o  m

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

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

    // 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);

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

    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    return urlConnection.getInputStream();

}