Example usage for javax.net.ssl HttpsURLConnection setDefaultHostnameVerifier

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

Introduction

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

Prototype

public static void setDefaultHostnameVerifier(HostnameVerifier v) 

Source Link

Document

Sets the default HostnameVerifier inherited by a new instance of this class.

Usage

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

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

    SSLContext sslContext = null;

    try {//w w  w .  j  av  a 2  s  .  c o m
        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.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;
        }//from   ww  w .  j av a  2 s  .  co 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();

}

From source file:com.athena.peacock.controller.common.component.RHEVMRestTemplate.java

/**
 * <pre>//from   ww w .j  a v a  2  s . c o  m
 *  ? ??   HTTPS   HandShake Exception ? ??  Exception? ? ?
 * RHEV Manager(host) ? SSL ??  ?   ? ?? ?.
 * </pre>
 * @throws Exception
 */
public void init() throws Exception {
    // http://javaresolutions.blogspot.kr/2014/07/javaxnetsslsslprotocolexception.html
    // -Djsse.enableSNIExtension=false
    // System.setProperty("jsse.enableSNIExtension", "false");

    System.setProperty("jsse.enableSNIExtension", "false");

    // Create a hostname verifier that does not validate hostname
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            /*
            if (hostname.equals(host)) {
            return true;
            }
                    
            return false;
            */
            return true;
        }
    });

    // Create a trust manager that does not validate certificate chains
    // Refer to https://code.google.com/p/misc-utils/wiki/JavaHttpsUrl
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // nothing to do.
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // nothing to do.
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };

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

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    } catch (KeyManagementException e) {
        logger.error("KeyManagementException has occurred.", e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("NoSuchAlgorithmException has occurred.", e);
    }
}

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   w ww  . j a  v a2 s. co  m*/
    }

    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: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 . java  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:org.wso2.automation.platform.tests.apim.is.SingleSignOnTestCase.java

@BeforeClass(alwaysRun = true)
public void init() throws APIManagerIntegrationTestException {

    super.init(TestUserMode.SUPER_TENANT_ADMIN);
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    DefaultHttpClient client = new DefaultHttpClient();

    SchemeRegistry registry = new SchemeRegistry();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    registry.register(new Scheme("https", socketFactory, 443));
    SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);

    httpClient = new DefaultHttpClient(mgr, client.getParams());

    CookieStore cookieStore = new BasicCookieStore();

    // Set verifier
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    AutomationContext isContext;/*from   w w w  . j a v a 2s.com*/
    httpsPublisherUrl = publisherUrls.getWebAppURLHttps() + "publisher";
    httpsStoreUrl = storeUrls.getWebAppURLHttps() + "store";
    try {
        providerName = publisherContext.getContextTenant().getContextUser().getUserName();
    } catch (XPathExpressionException e) {
        log.error(e);
        throw new APIManagerIntegrationTestException("Error while getting server url", e);
    }

    try {
        isContext = new AutomationContext("IS", "SP", TestUserMode.SUPER_TENANT_ADMIN);
        commonAuthUrl = isContext.getContextUrls().getBackEndUrl().replaceAll("services/", "") + "commonauth";
        samlSsoEndpointUrl = isContext.getContextUrls().getBackEndUrl().replaceAll("services/", "") + "samlsso";
    } catch (XPathExpressionException e) {
        log.error("Error initializing IS server details", e);
        throw new APIManagerIntegrationTestException("Error initializing IS server details", e);
    }

}

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:com.sitewhere.groovy.device.communication.rest.RestHelper.java

/**
 * Create SSL context that allows bad certificates.
 * //  www.  ja v a2  s  .c  o  m
 * @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:be.fedict.eid.idp.sp.protocol.openid.OpenIDSSLSocketFactory.java

/**
 * Installs the OpenID SSL Socket Factory. Trusts all server certificates.
 * For testing purposes only!//  w  ww.  ja v  a 2  s.  c  o 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.ibm.caas.CaaSResource.java

/**
 * Pass throughout CERTs [workaround]//w  w w. j  av a2s .c  om
 */
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();
    }
}