Example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER

List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER.

Prototype

X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER

To view the source code for org.apache.http.conn.ssl SSLConnectionSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER.

Click Source Link

Usage

From source file:ddu.core.httpclient.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    // Trust own CA and all self-signed certs
    KeyStore trustKeyStore = KeyStore.getInstance("JKS");

    // get user password and file input stream
    char[] password = "123456".toCharArray();
    java.io.FileInputStream fis = null;
    try {/*  w  w w. j  a va 2  s.  co  m*/
        fis = new java.io.FileInputStream("keyStoreName");
        trustKeyStore.load(fis, password);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }

    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustKeyStore, new TrustSelfSignedStrategy())
            .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpGet httpget = new HttpGet("https://httpbin.org/");

        System.out.println("Executing request " + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:co.cask.cdap.client.rest.RestUtil.java

public static Registry<ConnectionSocketFactory> getRegistryWithDisabledCertCheck()
        throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        @Override/*from w w  w.  j  a  v  a  2s. co  m*/
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }
    } }, new SecureRandom());
    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return RegistryBuilder.<ConnectionSocketFactory>create().register("https", sf)
            .register("http", PlainConnectionSocketFactory.getSocketFactory()).build();
}

From source file:com.vmware.bdd.cli.http.HostnameVerifiers.java

public X509HostnameVerifier getHostnameVerifier(String verifier) {
    switch (verifier) {
    case "browser_compatible":
        return SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
    case "strict":
        return SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;
    case "allow_all":
    default:/*from   www  .  j  a  va  2 s .  c o m*/
        return SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    }

}

From source file:utils.HttpClientGenerator.java

public static CloseableHttpClient getHttpClient(boolean checkCert) {

    if (checkCert == false) {
        HttpClientBuilder b = HttpClientBuilder.create();

        // setup a Trust Strategy that allows all certificates.
        SSLContext sslContext = null;
        try {//from   w  w w.j a v  a2s  . co m
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    return true;
                }
            }).build();
        } catch (NoSuchAlgorithmException e) {
            String err = "error occurred while creating SSL disables hhtp client";
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        b.setSslcontext(sslContext);

        // not to check Hostnames
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

        //       create an SSL Socket Factory, to use weakened "trust strategy";
        //       and create a Registry, to register it.
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                (X509HostnameVerifier) hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory).build();

        // creating connection-manager using our Registry.
        //      -- allows multi-threaded use
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(
                socketFactoryRegistry);
        connMgr.setDefaultMaxPerRoute(20);
        // Increase max connections for localhost:80 to 50
        HttpHost localhost = new HttpHost("localhost", 9443);
        connMgr.setMaxPerRoute(new HttpRoute(localhost), 10);
        b.setConnectionManager(connMgr);

        // finally, build the HttpClient;
        CloseableHttpClient client = b.build();
        return client;
    } else {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        // Increase default max connection per route to 20
        cm.setDefaultMaxPerRoute(20);
        // Increase max connections for localhost:80 to 50
        HttpHost localhost = new HttpHost("localhost", 9443);
        cm.setMaxPerRoute(new HttpRoute(localhost), 10);
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(cm).build();
        return client;
    }
}

From source file:org.jasig.cas.util.SimpleHttpClientTests.java

@Test
public void testBypassedInvalidHttpsUrl() throws Exception {
    final SimpleHttpClient client = new SimpleHttpClient(getFriendlyToAllSSLSocketFactory(),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER, new int[] { 200, 403 });
    assertTrue(client.isValidEndPoint("https://static.ak.connect.facebook.com"));
}

From source file:org.wso2.apim.billing.clients.APIRESTClient.java

public APIRESTClient(String host) {
    // TODO Auto-generated constructor stub
    httpClient = HttpClients.custom()/*ww  w  . ja va2  s . co m*/
            .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).build();

    loginUrl = host + "/store/site/blocks/user/login/ajax/login.jag";
    getSubsUrl = host + "/store/site/blocks/subscription/subscription-list/ajax/subscription-list.jag";
    appListUrl = host + "/store/site/blocks/application/application-list/ajax/application-list.jag";
    System.out.println("host " + host);
}

From source file:org.jwebsocket.sso.HTTPSupport.java

/**
 *
 * @param aURL//from   w  ww.  ja v a 2s .  c  o m
 * @param aMethod
 * @param aHeaders
 * @param aPostBody
 * @param aTimeout
 * @return
 */
public static String request(String aURL, String aMethod, Map<String, String> aHeaders, String aPostBody,
        long aTimeout) {
    if (mLog.isDebugEnabled()) {
        mLog.debug("Requesting (" + aMethod + ") '" + aURL + "', timeout: " + aTimeout + "ms, Headers: "
                + aHeaders + ", Body: "
                + (null != aPostBody ? "'" + aPostBody.replace("\n", "\\n").replace("\r", "\\r") + "'"
                        : "[null]"));
    }
    String lResponse = "{\"code\": -1, \"msg\": \"undefined\"";
    try {
        KeyStore lTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        lTrustStore.load(null, null);
        // Trust own CA and all self-signed certs
        SSLContext lSSLContext = SSLContexts.custom()
                .loadTrustMaterial(lTrustStore, new TrustSelfSignedStrategy()).build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory lSSLFactory = new SSLConnectionSocketFactory(lSSLContext,
                new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        CloseableHttpClient lHTTPClient = HttpClients.custom().setSSLSocketFactory(lSSLFactory).build();
        HttpUriRequest lRequest;
        if ("POST".equals(aMethod)) {
            lRequest = new HttpPost(aURL);
            ((HttpPost) lRequest).setEntity(new ByteArrayEntity(aPostBody.getBytes("UTF-8")));
        } else {
            lRequest = new HttpGet(aURL);
        }
        for (Map.Entry<String, String> lEntry : aHeaders.entrySet()) {
            lRequest.setHeader(lEntry.getKey(), lEntry.getValue());
        }

        // System.out.println("Executing request " + lRequest.getRequestLine());
        // Create a custom response handler
        ResponseHandler<String> lResponseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse lResponse)
                    throws ClientProtocolException, IOException {
                int lStatus = lResponse.getStatusLine().getStatusCode();
                HttpEntity lEntity = lResponse.getEntity();
                return lEntity != null ? EntityUtils.toString(lEntity) : null;

                //               if (lStatus >= 200 && lStatus < 300) {
                //                  HttpEntity entity = lResponse.getEntity();
                //                  return entity != null ? EntityUtils.toString(entity) : null;
                //               } else {
                //                  throw new ClientProtocolException("Unexpected response status: " + lStatus);
                //               }
            }

        };
        long lStartedAt = System.currentTimeMillis();
        lResponse = lHTTPClient.execute(lRequest, lResponseHandler);
        if (mLog.isDebugEnabled()) {
            mLog.debug("Response (" + (System.currentTimeMillis() - lStartedAt) + "ms): '"
                    + lResponse.replace("\n", "\\n").replace("\r", "\\r") + "'");
        }
        return lResponse;
    } catch (Exception lEx) {
        String lMsg = "{\"code\": -1, \"msg\": \"" + lEx.getClass().getSimpleName() + " at http request: "
                + lEx.getMessage() + "\"}";
        mLog.error(lEx.getClass().getSimpleName() + ": " + lEx.getMessage() + ", returning: " + lMsg);
        lResponse = lMsg;
        return lResponse;
    }
}

From source file:org.wso2.apim.billing.clients.DASRestClient.java

/**
 * get instance providing DAS configuration
 *
 * @param url  DAS rest api location//  w  ww. j  a v  a  2 s.  c  o  m
 * @param user DAS rest api username
 * @param pass DAs rest api password
 */
public DASRestClient(String url, String user, char[] pass) throws MalformedURLException {
    URL dasURL = new URL(url);
    httpClient = HttpClients.custom()
            .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).build();
    this.dasUrl = url;
    this.user = user;
    this.pass = pass;
}

From source file:nl.eveoh.mytimetable.apiclient.service.MyTimetableHttpClientBuilderImpl.java

private SSLConnectionSocketFactory createSslSocketFactory(Configuration configuration) {
    X509HostnameVerifier verifier;
    if (configuration.isApiSslCnCheck()) {
        verifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
    } else {/*ww w  .  j  ava 2  s  .  c  o m*/
        verifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    }

    return new SSLConnectionSocketFactory(SSLContexts.createSystemDefault(), verifier);
}

From source file:com.naver.timetable.bo.HttpClientBO.java

public String getHttpBody(String url, String method, List<NameValuePair> param) {
    HttpClient httpClient = null;//from   ww  w.j  a va2 s.  co m
    HttpResponse httpResponse = null;
    HttpRequestBase httpRequest;

    try {
        if (StringUtils.upperCase(method).equals("POST")) {
            httpRequest = new HttpPost(url);
            ((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(param));
        } else {
            httpRequest = new HttpGet(url);
        }

        TrustManager[] trustManagers = new TrustManager[1];
        trustManagers[0] = new DefaultTrustManager();

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(new KeyManager[0], trustManagers, new SecureRandom());
        SSLContext.setDefault(sslContext);

        sslContext.init(null, trustManagers, null);
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

        //         httpClient = HttpClientBuilder.create().build();
        httpResponse = httpClient.execute(httpRequest);
        return EntityUtils.toString(httpResponse.getEntity());
    } catch (ClientProtocolException e) {
        LOG.error("Client protocol error : ", e);
    } catch (IOException e) {
        LOG.error("IO error : ", e);
    } catch (KeyManagementException e) {
        LOG.error("IO error : ", e);
    } catch (NoSuchAlgorithmException e) {
        LOG.error("IO error : ", e);
    } finally {
        // ?
        HttpClientUtils.closeQuietly(httpResponse);
        HttpClientUtils.closeQuietly(httpClient);
    }

    return null;
}