Example usage for javax.net.ssl HostnameVerifier HostnameVerifier

List of usage examples for javax.net.ssl HostnameVerifier HostnameVerifier

Introduction

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

Prototype

HostnameVerifier

Source Link

Usage

From source file:org.openecomp.sdnc.sli.resource.mdsal.RestService.java

private Document send(String urlString, byte[] msgBytes, String method) {
    Document response = null;/*  www.  j a  v a 2 s.c  o  m*/
    String fullUrl = protocol + "://" + host + ":" + port + "/" + urlString;
    LOG.info("Sending REST " + method + " to " + fullUrl);

    if (msgBytes != null) {
        LOG.info("Message body:\n" + msgBytes);
    }

    try {
        HttpURLConnection conn = getRestConnection(fullUrl, method);

        if (conn instanceof HttpsURLConnection) {
            HostnameVerifier hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
            ((HttpsURLConnection) conn).setHostnameVerifier(hostnameVerifier);
        }

        // Write message
        if (msgBytes != null) {
            conn.setRequestProperty("Content-Length", "" + msgBytes.length);
            DataOutputStream outStr = new DataOutputStream(conn.getOutputStream());
            outStr.write(msgBytes);
            outStr.close();
        } else {
            conn.setRequestProperty("Content-Length", "0");
        }

        // Read response
        BufferedReader respRdr;

        LOG.info("Response: " + conn.getResponseCode() + " " + conn.getResponseMessage());

        if (conn.getResponseCode() < 300) {

            respRdr = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        } else {
            respRdr = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        }

        StringBuffer respBuff = new StringBuffer();

        String respLn;

        while ((respLn = respRdr.readLine()) != null) {
            respBuff.append(respLn + "\n");
        }
        respRdr.close();

        String respString = respBuff.toString();

        LOG.info("Response body :\n" + respString);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        response = db.parse(new ByteArrayInputStream(respString.getBytes()));

    } catch (Exception e) {

        LOG.error("Caught exception executing REST command", e);
    }

    return (response);
}

From source file:org.openhab.binding.ihc.ws.IhcConnectionPool.java

private void init() {

    // Create a local instance of cookie store
    cookieStore = new BasicCookieStore();

    // Create local HTTP context
    localContext = HttpClientContext.create();

    // Bind custom cookie store to the local context
    localContext.setCookieStore(cookieStore);

    httpClientBuilder = HttpClientBuilder.create();

    // Setup a Trust Strategy that allows all certificates.

    logger.debug("Initialize SSL context");

    // Create a trust manager that does not validate certificate chains,
    // but accept all.
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        @Override//from   w w  w .j  av  a 2s.  co  m
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            logger.trace("Trusting server cert: " + certs[0].getIssuerDN());
        }
    } };

    // Install the all-trusting trust manager

    try {
        // Controller supports only SSLv3 and TLSv1
        sslContext = SSLContext.getInstance("TLSv1");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    } catch (NoSuchAlgorithmException e) {
        logger.warn("Exception", e);
    } catch (KeyManagementException e) {
        logger.warn("Exception", e);
    }

    httpClientBuilder.setSslcontext(sslContext);

    // Controller accepts only HTTPS connections and because normally IP
    // address are used on home network rather than DNS names, create custom
    // host name verifier.
    HostnameVerifier hostnameVerifier = new HostnameVerifier() {

        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            logger.trace("HostnameVerifier: arg0 = " + arg0);
            logger.trace("HostnameVerifier: arg1 = " + arg1);
            return true;
        }
    };

    // Create an SSL Socket Factory, to use our weakened "trust strategy"
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            new String[] { "TLSv1" }, null, hostnameVerifier);

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslSocketFactory).build();

    // Create connection-manager using our Registry. Allows multi-threaded
    // use
    PoolingHttpClientConnectionManager connMngr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

    // Increase max connection counts
    connMngr.setMaxTotal(20);
    connMngr.setDefaultMaxPerRoute(6);

    httpClientBuilder.setConnectionManager(connMngr);
}

From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse postWithBasicAuth(String uri, String requestQuery, String userName, String password)
        throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        ;/*from  w ww. j av a2 s. co m*/
        conn.setRequestProperty("Authorization", "Basic " + encode);
        conn.setDoOutput(true); // Triggers POST.
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length));
        conn.setUseCaches(false);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(requestQuery);
        conn.setReadTimeout(10000);
        conn.connect();
        System.out.println(conn.getRequestMethod());
        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            return new HttpsResponse(sb.toString(), conn.getResponseCode());
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            wr.flush();
            wr.close();
            conn.disconnect();
        }
    }
    return null;
}

From source file:com.intuit.tank.okhttpclient.TankOkHttpClient.java

/**
 * no-arg constructor for OkHttp client/*w  w w  . j a va2  s. com*/
 */
public TankOkHttpClient() {
    try {

        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

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

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

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

        // Setup SSL to accept all certs
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, null);
        sslSocketFactory = sslContext.getSocketFactory();

        // Setup Cookie manager
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        CookieHandler.setDefault(cookieManager);
        okHttpClient.setCookieHandler(cookieManager);

        okHttpClient.setConnectTimeout(30000, TimeUnit.MILLISECONDS);
        okHttpClient.setReadTimeout(30000, TimeUnit.MILLISECONDS); // Socket-timeout
        okHttpClient.setFollowRedirects(true);
        okHttpClient.setFollowSslRedirects(true);

        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

    } catch (Exception e) {
        LOG.error("Error setting accept all: " + e, e);
    }
}

From source file:com.sitewhere.groovy.device.communication.rest.RestHelper.java

/**
 * Removes requirement for valid certificate on server.
 * /* ww w . j av  a  2  s .  co m*/
 * @return
 */
protected ClientHttpRequestFactory createSecureTransport() {
    HostnameVerifier nullHostnameVerifier = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    HttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(nullHostnameVerifier)
            .setSSLContext(createContext()).build();

    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client);

    return requestFactory;
}

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

/**
* Returns a hostname verifiers that always returns true, always positively verifies a host.
*//* w  w w .ja v  a  2 s .c om*/
public static HostnameVerifier getAllHostVerifier() {
    return new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
}

From source file:de.hybris.platform.marketplaceintegration.utils.impl.MarketplaceintegrationHttpUtilImpl.java

private void trustAllSSLCerts() throws NoSuchAlgorithmException, KeyManagementException {
    final TrustManager[] trustAllCerts = { new X509TrustManager() {
        @Override//from w w w  . ja va  2s  .co  m
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(final X509Certificate[] certs, final String authType) {
            //
        }

        @Override
        public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
            //
        }
    } };
    final SSLContext sc = SSLContext.getInstance("SSL");
    final HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(final String arg0, final SSLSession arg1) {
            return true;
        }
    };
    sc.init(null, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

From source file:org.flowable.ui.admin.service.engine.FlowableClientService.java

public CloseableHttpClient getHttpClient(String userName, String password) {

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));

    SSLConnectionSocketFactory sslsf = null;
    try {/*from   w ww  . j  a va  2s .  c o  m*/
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    } catch (Exception e) {
        LOGGER.warn("Could not configure HTTP client to use SSL", e);
    }

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    if (preemptiveBasicAuthentication) {
        String auth = userName + ":" + password;
        httpClientBuilder.setDefaultHeaders(Collections.singletonList(new BasicHeader(AUTH.WWW_AUTH_RESP,
                "Basic " + Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8)))));
    }

    if (sslsf != null) {
        httpClientBuilder.setSSLSocketFactory(sslsf);
    }

    return httpClientBuilder.build();
}

From source file:org.openmuc.framework.driver.rest.RestConnection.java

public RestConnection(String deviceAddress, String credentials, int timeout) throws ConnectionException {

    this.timeout = timeout;
    wrapper = new JsonWrapper();
    authString = new String(Base64.encodeBase64(credentials.getBytes()));

    if (!deviceAddress.endsWith("/")) {
        this.deviceAddress = deviceAddress + "/channels/";
    } else {// w w  w.j a v a2s  .c om
        this.deviceAddress = deviceAddress + "channels/";
    }

    if (deviceAddress.startsWith("https://")) {
        isHTTPS = true;
    } else {
        isHTTPS = false;
    }

    if (isHTTPS) {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            @Override
            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 (KeyManagementException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

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

        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        // HttpsURLConnection.setFollowRedirects(false);
    }
}