Example usage for javax.net.ssl HttpsURLConnection setHostnameVerifier

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

Introduction

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

Prototype

public void setHostnameVerifier(HostnameVerifier v) 

Source Link

Document

Sets the HostnameVerifier for this instance.

Usage

From source file:odata.service.util.Util.java

private static void disableSSLVerification(HttpsURLConnection connection) {
    connection.setHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }//from www. j a v  a 2 s.  com
    });
}

From source file:gov.nih.nci.cabig.ccts.security.SecureURL.java

/**
 * Retrieve the contents from the given URL as a String, assuming the URL's
 * server matches what we expect it to match.
 *//* w w w  .  j  av a2s.c  o m*/
public static String retrieve(String url) throws IOException {
    if (log.isTraceEnabled()) {
        log.trace("entering retrieve(" + url + ")");
    }
    BufferedReader r = null;
    try {
        URL u = new URL(url);
        if (!u.getProtocol().equals("https")) {
            // IOException may not be the best exception we could throw here
            // since the problem is with the URL argument we were passed,
            // not
            // IO. -awp9
            log.error("retrieve(" + url + ") on an illegal URL since protocol was not https.");
            throw new IOException("only 'https' URLs are valid for this method");
        }

        // JAP: changing to allow validation of Globus-style host names.
        // URLConnection uc = u.openConnection();
        HttpsURLConnection uc = (HttpsURLConnection) u.openConnection();
        uc.setHostnameVerifier(new HostnameVerifier() {

            public boolean verify(String hostname, SSLSession session) {
                boolean valid = false;
                try {
                    String expectedHostname = hostname.toLowerCase();
                    log.debug("expectedHostname = " + expectedHostname);

                    String subjectDN = session.getPeerCertificateChain()[0].getSubjectDN().getName()
                            .toLowerCase();
                    log.debug("subjectDN = " + subjectDN);
                    String assertedHostname = null;
                    for (String part : subjectDN.split(",")) {
                        String[] nameValue = part.split("=");
                        String name = nameValue[0].toLowerCase().trim();
                        String value = nameValue[1].trim();
                        if (name.equals("cn")) {
                            assertedHostname = value;
                            break;
                        }
                    }
                    if (assertedHostname == null) {
                        log.warn("No common name found in subject distinguished name.");
                        return false;
                    }
                    log.debug("assertedHostname = " + assertedHostname);
                    if (assertedHostname.startsWith("host/")) {
                        expectedHostname = "host/" + expectedHostname;
                        log.debug("detected Globus-style common name, expectedHostname = " + expectedHostname);
                    }
                    valid = assertedHostname.equals(expectedHostname);
                    log.debug("valid = " + valid);
                } catch (Exception ex) {
                    log.warn(ex);
                }
                return valid;
            }

        });

        uc.setRequestProperty("Connection", "close");
        r = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        String line;
        StringBuffer buf = new StringBuffer();
        while ((line = r.readLine()) != null)
            buf.append(line + "\n");
        return buf.toString();
    } finally {
        try {
            if (r != null)
                r.close();
        } catch (IOException ex) {
            // ignore
        }
    }
}

From source file:com.spotify.helios.client.DefaultHttpConnector.java

private static void handleHttps(final HttpURLConnection connection, final String hostname,
        final HostnameVerifierProvider hostnameVerifierProvider, final HttpsHandler extraHttpsHandler) {

    if (!(connection instanceof HttpsURLConnection)) {
        return;//from w  ww . j a v  a2s  . co m
    }

    // We verify the TLS certificate against the original hostname since verifying against the
    // IP address will fail
    System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
    connection.setRequestProperty("Host", hostname);

    final HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
    httpsConnection.setHostnameVerifier(hostnameVerifierProvider.verifierFor(hostname));

    if (extraHttpsHandler != null) {
        extraHttpsHandler.handle(httpsConnection);
    }
}

From source file:com.photon.phresco.nativeapp.eshop.net.NetworkManager.java

public static boolean checkHttpsURLStatus(final String url) {
    boolean https_StatusFlag = false;
    System.out.println("Entered in checkHttpsURLStatus >>>>>>>>>>>>>>>");

    URL httpsurl;//from w w w.ja  v  a2  s . c o  m
    try {

        // Create a context that doesn't check certificates.
        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());
        System.out.println("Url =========" + url);
        httpsurl = new URL(url);

        HttpsURLConnection con = (HttpsURLConnection) httpsurl.openConnection();
        con.setHostnameVerifier(DO_NOT_VERIFY);
        int statusCode = con.getResponseCode();
        System.out.println("statusCode =========" + statusCode);

        if (statusCode == HttpURLConnection.HTTP_OK) {

            https_StatusFlag = true;

        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    return https_StatusFlag;
}

From source file:org.apache.hadoop.hdfs.web.URLConnectionFactory.java

/**
 * Create a new ConnectionConfigurator for SSL connections
 *//*from w w  w . jav  a 2s.  co  m*/
private static ConnectionConfigurator newSslConnConfigurator(final int timeout, Configuration conf)
        throws IOException, GeneralSecurityException {
    final SSLFactory factory;
    final SSLSocketFactory sf;
    final HostnameVerifier hv;

    factory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
    factory.init();
    sf = factory.createSSLSocketFactory();
    hv = factory.getHostnameVerifier();

    return new ConnectionConfigurator() {
        @Override
        public HttpURLConnection configure(HttpURLConnection conn) throws IOException {
            if (conn instanceof HttpsURLConnection) {
                HttpsURLConnection c = (HttpsURLConnection) conn;
                c.setSSLSocketFactory(sf);
                c.setHostnameVerifier(hv);
            }
            URLConnectionFactory.setTimeouts(conn, timeout);
            return conn;
        }
    };
}

From source file:io.fabric8.apiman.gateway.ApimanGatewayStarter.java

private static URL waitForDependency(URL url, String serviceName, String key, String value, String username,
        String password) throws InterruptedException {
    boolean isFoundRunningService = false;
    ObjectMapper mapper = new ObjectMapper();
    int counter = 0;
    URL endpoint = null;/*from   www  .j  a va  2 s .  c o  m*/
    while (!isFoundRunningService) {
        endpoint = resolveServiceEndpoint(url.getProtocol(), url.getHost(), String.valueOf(url.getPort()));
        if (endpoint != null) {
            String isLive = null;
            try {
                URL statusURL = new URL(endpoint.toExternalForm() + url.getPath());
                HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection();
                urlConnection.setConnectTimeout(500);
                if (urlConnection instanceof HttpsURLConnection) {
                    try {
                        KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(TRUSTSTORE_PATH,
                                TRUSTSTORE_PASSWORD_PATH);
                        TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo);
                        KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info(CLIENT_KEYSTORE_PATH,
                                CLIENT_KEYSTORE_PASSWORD_PATH);
                        KeyManager[] kms = KeyStoreUtil.getKeyManagers(kPathInfo);
                        final SSLContext sc = SSLContext.getInstance("TLS");
                        sc.init(kms, tms, new java.security.SecureRandom());
                        final SSLSocketFactory socketFactory = sc.getSocketFactory();
                        HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
                        HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
                        httpsConnection.setHostnameVerifier(new DefaultHostnameVerifier());
                        httpsConnection.setSSLSocketFactory(socketFactory);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        throw e;
                    }
                }
                if (Utils.isNotNullOrEmpty(username)) {
                    String encoded = Base64.getEncoder()
                            .encodeToString((username + ":" + password).getBytes("UTF-8"));
                    log.info(username + ":******");
                    urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
                }
                isLive = IOUtils.toString(urlConnection.getInputStream());
                Map<String, Object> esResponse = mapper.readValue(isLive,
                        new TypeReference<Map<String, Object>>() {
                        });
                if (esResponse.containsKey(key) && value.equals(String.valueOf(esResponse.get(key)))) {
                    isFoundRunningService = true;
                } else {
                    if (counter % 10 == 0)
                        log.info(endpoint.toExternalForm() + " not yet up (host=" + endpoint.getHost() + ")"
                                + isLive);
                }
            } catch (Exception e) {
                if (counter % 10 == 0)
                    log.info(endpoint.toExternalForm() + " not yet up. (host=" + endpoint.getHost() + ")"
                            + e.getMessage());
            }
        } else {
            if (counter % 10 == 0)
                log.info("Could not find " + serviceName + " in namespace, waiting..");
        }
        counter++;
        Thread.sleep(1000l);
    }
    return endpoint;
}

From source file:och.util.NetUtil.java

public static HttpURLConnection setTrustAnyHttps(HttpURLConnection conn) {

    if (trustAllSocketFactory == null) {
        log.error("can't setTrustAnyHttps for " + conn);
        return conn;
    }/*from   ww w  . j  a v  a 2  s . c  om*/

    if (conn instanceof HttpsURLConnection) {
        HttpsURLConnection https = (HttpsURLConnection) conn;
        https.setSSLSocketFactory(trustAllSocketFactory);
        https.setHostnameVerifier(allHostVerifier);
    }
    return conn;
}

From source file:org.apache.atlas.security.SecureClientUtils.java

private static ConnectionConfigurator newSslConnConfigurator(final int timeout, Configuration conf)
        throws IOException, GeneralSecurityException {
    final SSLFactory factory;
    final SSLSocketFactory sf;
    final HostnameVerifier hv;

    factory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
    factory.init();/*  w ww  .j a va  2 s  .c om*/
    sf = factory.createSSLSocketFactory();
    hv = factory.getHostnameVerifier();

    return new ConnectionConfigurator() {
        @Override
        public HttpURLConnection configure(HttpURLConnection conn) throws IOException {
            if (conn instanceof HttpsURLConnection) {
                HttpsURLConnection c = (HttpsURLConnection) conn;
                c.setSSLSocketFactory(sf);
                c.setHostnameVerifier(hv);
            }
            setTimeouts(conn, timeout);
            return conn;
        }
    };
}

From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java

public static String fetchSecureContent(final String url, final int timeout) throws IOException {
    LOGGER.info("fetchSecureContent: " + url);
    final URL u = new URL(url);
    final URLConnection conn = u.openConnection();
    if (timeout != 0) {
        conn.setConnectTimeout(timeout);
        conn.setReadTimeout(timeout);/*www  .jav  a 2  s. co m*/
    }
    if (conn instanceof HttpsURLConnection) {
        final HttpsURLConnection http = (HttpsURLConnection) conn;
        http.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(final String arg0, final SSLSession arg1) {
                return true;
            }
        });
        http.setRequestMethod(GET_STR);
        http.setAllowUserInteraction(true);
    }
    return IOUtils.toString(conn.getInputStream());
}

From source file:org.apache.hadoop.hdfsproxy.ProxyUtil.java

private static HttpsURLConnection openConnection(String hostname, int port, String path) throws IOException {
    try {/*from   w ww.j a  v  a2s . c  o  m*/
        final URL url = new URI("https", null, hostname, port, path, null, null).toURL();
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        // bypass hostname verification
        conn.setHostnameVerifier(new DummyHostnameVerifier());
        conn.setRequestMethod("GET");
        return conn;
    } catch (URISyntaxException e) {
        throw (IOException) new IOException().initCause(e);
    }
}