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.zlk.bigdemo.android.volley.toolbox.HurlStack.java

/**
 * Opens an {@link HttpURLConnection} with parameters.
 * @param url/*from  w  w  w.  ja v  a2  s  .co m*/
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}

From source file:com.jaspersoft.jrx.query.JRXPathQueryExecuter.java

private Document getDocumentFromUrl(Map<String, ? extends JRValueParameter> parametersMap) throws Exception {
    // Get the url...
    String urlString = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_URL);

    // add GET parameters to the urlString...
    Iterator<String> i = parametersMap.keySet().iterator();

    String div = "?";
    URL url = new URL(urlString);
    if (url.getQuery() != null)
        div = "&";

    while (i.hasNext()) {
        String keyName = "" + i.next();
        if (keyName.startsWith("XML_GET_PARAM_")) {
            String paramName = keyName.substring("XML_GET_PARAM_".length());
            String value = (String) getParameterValue(keyName);

            urlString += div + URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8");
            div = "&";
        }/*from   w w  w.j a  va  2s .  c  om*/
    }

    url = new URL(urlString);

    if (url.getProtocol().toLowerCase().equals("file")) {
        // do nothing
        return JRXmlUtils.parse(url.openStream());
    } else if (url.getProtocol().toLowerCase().equals("http")
            || url.getProtocol().toLowerCase().equals("https")) {
        String username = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_USERNAME);
        String password = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_PASSWORD);

        if (url.getProtocol().toLowerCase().equals("https")) {
            JRPropertiesUtil dPROP = PropertiesHelper.DPROP;
            String socketFactory = dPROP
                    .getProperty("net.sf.jasperreports.query.executer.factory.xPath.DefaultSSLSocketFactory");
            if (socketFactory == null) {
                socketFactory = dPROP.getProperty(
                        "net.sf.jasperreports.query.executer.factory.XPath.DefaultSSLSocketFactory");
            }

            if (socketFactory != null) {
                // setSSLSocketFactory
                HttpsURLConnection.setDefaultSSLSocketFactory(
                        (SSLSocketFactory) Class.forName(socketFactory).newInstance());
            } else {
                log.debug("No SSLSocketFactory defined, using default");
            }

            String hostnameVerifyer = dPROP
                    .getProperty("net.sf.jasperreports.query.executer.factory.xPath.DefaultHostnameVerifier");
            if (hostnameVerifyer == null) {
                hostnameVerifyer = dPROP.getProperty(
                        "net.sf.jasperreports.query.executer.factory.XPath.DefaultHostnameVerifier");
            }

            if (hostnameVerifyer != null) {
                // setSSLSocketFactory
                HttpsURLConnection.setDefaultHostnameVerifier(
                        (HostnameVerifier) Class.forName(hostnameVerifyer).newInstance());
            } else {
                log.debug("No HostnameVerifier defined, using default");
            }
        }

        URLConnection conn = url.openConnection();

        if (username != null && username.length() > 0 && password != null) {
            ByteArrayInputStream bytesIn = new ByteArrayInputStream((username + ":" + password).getBytes());
            ByteArrayOutputStream dataOut = new ByteArrayOutputStream();
            Base64Encoder enc = new Base64Encoder(bytesIn, dataOut);
            enc.process();
            String encoding = dataOut.toString();
            conn.setRequestProperty("Authorization", "Basic " + encoding);
        }

        // add POST parameters to the urlString...
        i = parametersMap.keySet().iterator();

        String data = "";
        div = "";
        while (i.hasNext()) {
            String keyName = "" + i.next();
            if (keyName.startsWith("XML_POST_PARAM_")) {
                String paramName = keyName.substring("XML_POST_PARAM_".length());
                String value = (String) getParameterValue(keyName);
                data += div + URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8");
                div = "&";
            }
        }

        conn.setDoOutput(true);

        if (data.length() > 0) {
            conn.setDoInput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();
        }

        try {
            return XMLUtils.parseNoValidation(conn.getInputStream());
        } catch (SAXException e) {
            throw new JRException("Failed to parse the xml document", e);
        } catch (IOException e) {
            throw new JRException("Failed to parse the xml document", e);
        } catch (ParserConfigurationException e) {
            throw new JRException("Failed to create a document builder factory", e);
        }

        // return JRXmlUtils.parse(conn.getInputStream());
    } else {
        throw new JRException("URL protocol not supported");
    }
}

From source file:com.scsy150.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 w  ww  .  j  ava  2s . c om*/
            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) {
            LogUtil.e("", e.getMessage());
        }
    }

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

From source file:com.vimc.ahttp.HurlWorker.java

private void setDefaultSSLSocketFactory() {
    SSLContext sslContext = null;
    try {/*from ww w .  j a v  a 2  s.  com*/
        X509TrustManagerImpl mtm = new X509TrustManagerImpl();
        TrustManager[] tms = new TrustManager[] { mtm };

        // ?X509TrustManagerSSLContext
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tms, new java.security.SecureRandom());
    } catch (Exception e) {
        e.printStackTrace();
    }

    // javax.net.ssl.HttpsURLConnectionSocketFactoryHostnameVerifier
    if (sslContext != null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    }
    X509HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
}

From source file:net.myrrix.client.ClientRecommender.java

private SSLSocketFactory buildSSLSocketFactory() throws IOException {

    final HostnameVerifier defaultVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override/*from   www .  j a  v  a 2  s .  c o m*/
        public boolean verify(String hostname, SSLSession sslSession) {
            return ignoreHTTPSHost || "localhost".equals(hostname) || "127.0.0.1".equals(hostname)
                    || defaultVerifier.verify(hostname, sslSession);
        }
    });

    try {

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        File trustStoreFile = config.getKeystoreFile().getAbsoluteFile();
        String password = config.getKeystorePassword();
        Preconditions.checkNotNull(password);

        InputStream in = new FileInputStream(trustStoreFile);
        try {
            keyStore.load(in, password.toCharArray());
        } finally {
            in.close();
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);

        SSLContext ctx;
        try {
            ctx = SSLContext.getInstance("TLSv1.1"); // Java 7 only
        } catch (NoSuchAlgorithmException ignored) {
            log.info("TLSv1.1 unavailable, falling back to TLSv1");
            ctx = SSLContext.getInstance("TLSv1"); // Java 6       
            // This also seems to be necessary:
            if (System.getProperty("https.protocols") == null) {
                System.setProperty("https.protocols", "TLSv1");
            }
        }
        ctx.init(null, tmf.getTrustManagers(), null);
        return ctx.getSocketFactory();

    } catch (NoSuchAlgorithmException nsae) {
        // can't happen?
        throw new IllegalStateException(nsae);
    } catch (KeyStoreException kse) {
        throw new IOException(kse);
    } catch (KeyManagementException kme) {
        throw new IOException(kme);
    } catch (CertificateException ce) {
        throw new IOException(ce);
    }
}

From source file:com.example.zch.imspeak.utils.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  ww . ja  va 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) {
            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.lidroid.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/*  ww  w .j  a v a2  s. co 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) {
            Logger.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:org.apache.fineract.infrastructure.sms.scheduler.SmsMessageScheduledJobServiceImpl.java

/** 
 * prevents the SSL security certificate check 
 **//*from ww w .j a va2 s  .  c o  m*/
private void trustAllSSLCertificates() {
    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) {
        }
    } };

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

        // Create all-trusting host name verifier
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

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

    catch (Exception e) {
        // do nothing
    }
}

From source file:www.ht.com.app.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  a  v  a  2s  . co 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) {
            Logger.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.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 a va 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);
    }
}