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: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 a v a 2s .  c  om
            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:ch.lipsch.subsonic4j.internal.SubsonicServiceImpl.java

private synchronized void allowUntrustedCerts() throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
    SSLContext.setDefault(ctx);/*from  ww w .  ja v a 2s.  c  o m*/

    HostnameVerifier hv = new HostnameVerifier() {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

From source file:com.microfocus.application.automation.tools.srf.run.RunFromSrfBuilder.java

public static JSONObject getSrfConnectionData(AbstractBuild<?, ?> build, PrintStream logger) {
    try {//from w  ww  . j  a va  2  s .  c om
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        String path = build.getProject().getParent().getRootDir().toString();
        path = path.concat(
                "/com.microfocus.application.automation.tools.srf.settings.SrfServerSettingsBuilder.xml");
        File file = new File(path);
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(file);
        // This also shows how you can consult the global configuration of the builder
        JSONObject connectionData = new JSONObject();

        String credentialsId = document.getElementsByTagName("credentialsId").item(0).getTextContent();
        UsernamePasswordCredentials credentials = CredentialsProvider.findCredentialById(credentialsId,
                StandardUsernamePasswordCredentials.class, build, URIRequirementBuilder.create().build());

        String app = credentials.getUsername();
        String tenant = app.substring(1, app.indexOf('_'));
        String secret = credentials.getPassword().getPlainText();
        String server = document.getElementsByTagName("srfServerName").item(0).getTextContent();

        // Normalize SRF server URL string if needed
        if (server.substring(server.length() - 1).equals("/")) {
            server = server.substring(0, server.length() - 1);
        }

        boolean https = true;
        if (!server.startsWith("https://")) {
            if (!server.startsWith("http://")) {
                String tmp = server;
                server = "https://";
                server = server.concat(tmp);
            } else
                https = false;
        }
        URL urlTmp = new URL(server);
        if (urlTmp.getPort() == -1) {
            if (https)
                server = server.concat(":443");
            else
                server = server.concat(":80");
        }
        String srfProxy = "";
        String srfTunnel = "";
        try {
            srfProxy = document.getElementsByTagName("srfProxyName").item(0) != null
                    ? document.getElementsByTagName("srfProxyName").item(0).getTextContent().trim()
                    : null;
            srfTunnel = document.getElementsByTagName("srfTunnelPath").item(0) != null
                    ? document.getElementsByTagName("srfTunnelPath").item(0).getTextContent()
                    : null;
        } catch (Exception e) {
            throw e;
        }
        connectionData.put("app", app);
        connectionData.put("tunnel", srfTunnel);
        connectionData.put("secret", secret);
        connectionData.put("server", server);
        connectionData.put("https", (https) ? "True" : "False");
        connectionData.put("proxy", srfProxy);
        connectionData.put("tenant", tenant);
        return connectionData;
    } catch (ParserConfigurationException e) {
        logger.print(e.getMessage());
        logger.print("\n\r");
    } catch (SAXException | IOException e) {
        logger.print(e.getMessage());
    }
    return null;
}

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//  w w w  .j av a  2 s  .  c o  m
            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:com.hpe.application.automation.tools.srf.run.RunFromSrfBuilder.java

public static JSONObject getSrfConnectionData(AbstractBuild<?, ?> build, PrintStream logger) {
    try {//from   w w  w.  j a v  a 2 s  .  co  m
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        String path = build.getProject().getParent().getRootDir().toString();
        path = path.concat("/com.hpe.application.automation.tools.settings.SrfServerSettingsBuilder.xml");
        File file = new File(path);
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(file);
        // This also shows how you can consult the global configuration of the builder
        JSONObject connectionData = new JSONObject();

        String app = document.getElementsByTagName("srfAppName").item(0).getTextContent();
        String tenant = app.substring(1, app.indexOf('_'));
        String secret = document.getElementsByTagName("srfSecretName").item(0).getTextContent();
        String server = document.getElementsByTagName("srfServerName").item(0).getTextContent();
        boolean https = true;
        if (!server.startsWith("https://")) {
            if (!server.startsWith("http://")) {
                String tmp = server;
                server = "https://";
                server = server.concat(tmp);
            } else
                https = false;
        }
        URL urlTmp = new URL(server);
        if (urlTmp.getPort() == -1) {
            if (https)
                server = server.concat(":443");
            else
                server = server.concat(":80");
        }
        String srfProxy = "";
        String srfTunnel = "";
        try {
            srfProxy = document.getElementsByTagName("srfProxyName").item(0).getTextContent().trim();
            srfTunnel = document.getElementsByTagName("srfTunnelPath").item(0).getTextContent();
        } catch (Exception e) {
            throw e;
        }
        connectionData.put("app", app);
        connectionData.put("tunnel", srfTunnel);
        connectionData.put("secret", secret);
        connectionData.put("server", server);
        connectionData.put("https", (https) ? "True" : "False");
        connectionData.put("proxy", srfProxy);
        connectionData.put("tenant", tenant);
        return connectionData;
    } catch (ParserConfigurationException e) {
        logger.print(e.getMessage());
        logger.print("\n\r");
    } catch (SAXException | IOException e) {
        logger.print(e.getMessage());
    }
    return null;
}

From source file:org.wso2.carbon.dynamic.client.web.app.registration.util.RemoteDCRClient.java

private static DefaultHttpClient getHTTPSClient() {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    // Setup the HTTPS settings to accept any certificate.
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    SchemeRegistry registry = new SchemeRegistry();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    registry.register(new Scheme(
            DynamicClientWebAppRegistrationConstants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_PROTOCOL,
            socketFactory, getServerHTTPSPort()));
    SingleClientConnManager mgr = new SingleClientConnManager(httpClient.getParams(), registry);
    httpClient = new DefaultHttpClient(mgr, httpClient.getParams());

    // Set verifier
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
    return httpClient;
}

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

/**
 * Code of this method was simply Googled.
 *///from   w  ww.  j  ava  2 s  .co  m
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:luki.x.net.XNetEngine.java

private void setDefaultHostnameVerifier() {
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }//from  w w  w.ja va 2 s. c  om
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

From source file:info.semanticsoftware.semassist.android.activity.AuthenticationActivity.java

private String authenicate(String username, String password) {
    String uri = serverURL + "/user";
    Log.d(Constants.TAG, uri);/*from  w  ww.  j a  va2s.c om*/
    String request = "<authenticate><username>" + username + "</username><password>" + password
            + "</password></authenticate>";
    Representation representation = new StringRepresentation(request, MediaType.APPLICATION_XML);
    String serverResponse = null;

    if (serverURL.indexOf("https") < 0) {
        Log.i(TAG, "Sending authentication request to " + uri);
        Representation response = new ClientResource(uri).post(representation);
        try {
            StringWriter writer = new StringWriter();
            response.write(writer);
            serverResponse = writer.toString();
            Log.i(TAG, "Authentication response: " + serverResponse);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        try {
            Log.i(TAG, "Sending authentication request to " + uri);
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            DefaultHttpClient client = new DefaultHttpClient();

            SchemeRegistry registry = new SchemeRegistry();
            final KeyStore ks = KeyStore.getInstance("BKS");
            // NOTE: the keystore must have been generated with BKS 146 and not later
            final InputStream in = getApplicationContext().getResources()
                    .openRawResource(R.raw.clientkeystorenew);
            try {
                ks.load(in, getString(R.string.keystorePassword).toCharArray());
            } finally {
                in.close();
            }

            SSLSocketFactory socketFactory = new CustomSSLSocketFactory(ks);
            socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
            registry.register(new Scheme("https", socketFactory, 443));
            SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
            DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

            // Set verifier
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

            HttpPost post = new HttpPost(uri);
            post.setEntity(new StringEntity(representation.getText()));

            HttpResponse response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            InputStream inputstream = entity.getContent();
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

            String string = null;
            while ((string = bufferedreader.readLine()) != null) {
                serverResponse += string;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return serverResponse;
}

From source file:com.tsavo.trade.TradeBot.java

public static void initSSL() throws KeyManagementException, NoSuchAlgorithmException {

    // SSL Certificates trustStore ----------------------------------------
    // Set the SSL certificate for mtgox - Read up on Java Trust store.
    // System.setProperty("javax.net.ssl.trustStore", "trader.jks");
    // System.setProperty("javax.net.ssl.trustStorePassword", "zabbas"); //
    // I/*www.  ja va2  s  . c o  m*/

    class MyManager implements X509TrustManager {

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

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

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

        }

    }

    TrustManager[] managers = new TrustManager[] { new MyManager() };
    final SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, managers, new SecureRandom());

    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    // System.setProperty("javax.net.debug","ssl"); //Uncomment for
    // debugging SSL errors

}