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:org.wso2.apim.billing.services.impl.WorkflowClientImpl.java

private HttpResponse sendPOSTMessage(String url, List<NameValuePair> headers, List<NameValuePair> urlParameters)
        throws Exception {
    CloseableHttpClient httpClient = HttpClients.custom()
            .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).build();
    HttpPost post = new HttpPost(url);
    if (headers != null) {
        for (NameValuePair nameValuePair : headers) {
            post.addHeader(nameValuePair.getName(), nameValuePair.getValue());
        }//from   w w  w . j ava 2  s.  c om
    }
    post.setEntity(new UrlEncodedFormEntity(urlParameters));
    return httpClient.execute(post);
}

From source file:sachin.spider.WebSpider.java

/**
 *
 * @param config//from   w w w .  java  2s .c  o  m
 * @param latch
 */
@SuppressWarnings("deprecation")
public void setValues(SpiderConfig config, CountDownLatch latch) {
    try {
        this.config = config;
        this.latch = latch;
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setUserAgent(config.getUserAgentString());
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(java.security.cert.X509Certificate[] xcs, String string)
                    throws java.security.cert.CertificateException {
                return true;
            }
        }).build();
        builder.setSslcontext(sslContext);
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory).build();
        cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        cm.setDefaultMaxPerRoute(config.getTotalSpiders() * 2);
        cm.setMaxTotal(config.getTotalSpiders() * 2);
        if (config.isAuthenticate()) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(config.getUsername(), config.getPassword()));
            httpclient = HttpClients.custom().setUserAgent(config.getUserAgentString())
                    .setDefaultCredentialsProvider(credentialsProvider).setConnectionManager(cm).build();

        } else {
            httpclient = HttpClients.custom().setConnectionManager(cm).setUserAgent(config.getUserAgentString())
                    .build();
        }
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        Logger.getLogger(WebSpider.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.jboss.arquillian.ce.httpclient.HttpClientBuilder.java

public HttpClientBuilder untrustedConnectionClientBuilder() throws Exception {
    // setup a Trust Strategy that allows all certificates.
    ////from w w w.ja v  a2  s. co  m
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                throws java.security.cert.CertificateException {
            return true;
        }

    }).build();
    builder.setSslcontext(sslContext);

    // don't check Hostnames, either.
    //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
    HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our 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();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    builder.setConnectionManager(connMgr);

    // finally, build the HttpClient;
    //      -- done!
    return this;
}

From source file:com.jaspersoft.studio.server.protocol.restv2.CASUtil.java

public static String doGetTocken(ServerProfile sp, SSOServer srv, IProgressMonitor monitor) throws Exception {
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            // System.out.println("getAcceptedIssuers =============");
            return null;
        }//from   w w  w.  ja  v a  2s.co  m

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("checkClientTrusted =============");
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("checkServerTrusted =============");
        }
    } }, new SecureRandom());

    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
            .setRedirectStrategy(new DefaultRedirectStrategy() {
                @Override
                protected boolean isRedirectable(String arg0) {
                    // TODO Auto-generated method stub
                    return super.isRedirectable(arg0);
                }

                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    // TODO Auto-generated method stub
                    return super.isRedirected(request, response, context);
                }
            }).setDefaultCookieStore(new BasicCookieStore())
            .setUserAgent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0")
            .build();

    Executor exec = Executor.newInstance(httpclient);

    URIBuilder ub = new URIBuilder(sp.getUrl() + "index.html");

    String fullURL = ub.build().toASCIIString();
    Request req = HttpUtils.get(fullURL, sp);
    HttpHost proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    String tgtID = readData(exec, req, monitor);
    String action = getFormAction(tgtID);
    if (action != null) {
        action = action.replaceFirst("/", "");
        int indx = action.indexOf(";jsession");
        if (indx >= 0)
            action = action.substring(0, indx);
    } else
        action = "cas/login";
    String url = srv.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub = new URIBuilder(url + action);
    //
    fullURL = ub.build().toASCIIString();
    req = HttpUtils.get(fullURL, sp);
    proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    tgtID = readData(exec, req, monitor);
    action = getFormAction(tgtID);
    action = action.replaceFirst("/", "");

    ub = new URIBuilder(url + action);
    Map<String, String> map = getInputs(tgtID);
    Form form = Form.form();
    for (String key : map.keySet()) {
        if (key.equals("btn-reset"))
            continue;
        else if (key.equals("username")) {
            form.add(key, srv.getUser());
            continue;
        } else if (key.equals("password")) {
            form.add(key, Pass.getPass(srv.getPassword()));
            continue;
        }
        form.add(key, map.get(key));
    }
    //
    req = HttpUtils.post(ub.build().toASCIIString(), form, sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // Header header = null;
    readData(exec, req, monitor);
    // for (Header h : headers) {
    // for (HeaderElement he : h.getElements()) {
    // if (he.getName().equals("CASTGC")) {
    // header = new BasicHeader("Cookie", h.getValue());
    // break;
    // }
    // }
    // }
    ub = new URIBuilder(url + action);
    url = sp.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub.addParameter("service", url + "j_spring_security_check");

    req = HttpUtils.get(ub.build().toASCIIString(), sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // req.addHeader("Accept",
    // "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8, value");
    req.addHeader("Referrer", sp.getUrl());
    // req.addHeader(header);
    String html = readData(exec, req, monitor);
    Matcher matcher = ahrefPattern.matcher(html);
    while (matcher.find()) {
        Map<String, String> attributes = parseAttributes(matcher.group(1));
        String v = attributes.get("href");
        int ind = v.indexOf("ticket=");
        if (ind > 0) {
            return v.substring(ind + "ticket=".length());
        }
    }
    return null;
}

From source file:nya.miku.wishmaster.http.client.ExtendedHttpClient.java

/**
 *   ? SSL//from  ww w.j  av  a  2 s  . c om
 * @param safe ??, ? false,    ?  
 */
private static LayeredConnectionSocketFactory obtainSSLSocketFactory(boolean safe) {
    if (safe) {
        return SSLConnectionSocketFactory.getSocketFactory();
    } else {
        try {
            if (unsafe_ssl_context == null)
                unsafe_ssl_context = SSLContexts.custom().loadTrustMaterial(null, TRUST_ALL).build();
            return new SSLConnectionSocketFactory(unsafe_ssl_context,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        } catch (Exception e) {
            Logger.e(TAG, "cannot instantiate the unsafe SSL socket factory", e);
            return SSLConnectionSocketFactory.getSocketFactory();
        }
    }
}

From source file:majordodo.client.http.Client.java

private void createClient() {

    try {/*  ww w  .j  a v  a 2 s .c  o  m*/
        SSLContext sslContext;
        SSLConnectionSocketFactory sslsf;
        if (configuration.isDisableHttpsVerification()) {
            sslContext = SSLContext.getInstance("SSL");
            TrustManager mytm[] = { new MyTrustManager() };
            sslContext.init(null, mytm, null);
            sslsf = new SSLConnectionSocketFactory(sslContext,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        } else {
            sslContext = SSLContexts.custom().build();
            sslsf = new SSLConnectionSocketFactory(sslContext,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        }

        Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", new PlainConnectionSocketFactory()).register("https", sslsf).build();

        poolManager = new PoolingHttpClientConnectionManager(r);

        if (configuration.getMaxConnTotal() > 0) {
            poolManager.setMaxTotal(configuration.getMaxConnTotal());
        }
        if (configuration.getMaxConnPerRoute() > 0) {
            poolManager.setDefaultMaxPerRoute(configuration.getMaxConnPerRoute());
        }

        poolManager.setDefaultSocketConfig(SocketConfig.custom().setSoKeepAlive(true).setSoReuseAddress(true)
                .setTcpNoDelay(false).setSoTimeout(configuration.getSotimeout()).build());

        ConnectionKeepAliveStrategy myStrategy = (HttpResponse response, HttpContext context) -> configuration
                .getKeepAlive();

        httpclient = HttpClients.custom().setConnectionManager(poolManager)
                .setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE)
                .setKeepAliveStrategy(myStrategy).build();
    } catch (NoSuchAlgorithmException | KeyManagementException ex) {
        throw new RuntimeException(ex);
    }

}

From source file:com.activiti.service.activiti.ActivitiClientService.java

public CloseableHttpClient getHttpClient(String userName, String password) {

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

    SSLConnectionSocketFactory sslsf = null;
    try {/* w  ww .j a  v  a 2s  .  c om*/
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Exception e) {
        log.warn("Could not configure HTTP client to use SSL", e);
    }

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

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

    return httpClientBuilder.build();
}

From source file:com.emc.storageos.driver.dellsc.scapi.rest.RestClient.java

/**
 * Instantiates a new Rest client./* w w  w .j  a va2s .  c  om*/
 *
 * @param host Host name or IP address of the Dell Storage Manager server.
 * @param port Port the DSM data collector is listening on.
 * @param user The DSM user name to use.
 * @param password The DSM password.
 */
public RestClient(String host, int port, String user, String password) {
    this.baseUrl = String.format("https://%s:%d/api/rest", host, port);

    try {
        // Set up auth handling
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, port),
                new UsernamePasswordCredentials(user, password));
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        HttpHost target = new HttpHost(host, port, "https");
        authCache.put(target, basicAuth);

        // Set up our context
        httpContext = HttpClientContext.create();
        httpContext.setCookieStore(new BasicCookieStore());
        httpContext.setAuthCache(authCache);

        // Create our HTTPS client
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        this.httpClient = HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier())
                .setDefaultCredentialsProvider(credsProvider).setSSLSocketFactory(sslSocketFactory).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        // Hopefully default SSL handling is set up
        LOG.warn("Failed to configure HTTP handling, falling back to default handler.");
        LOG.debug("Config error: {}", e);
        this.httpClient = HttpClients.createDefault();
    }
}

From source file:net.ymate.platform.module.wechat.support.HttpClientHelper.java

private CloseableHttpClient __doBuildHttpClient() throws KeyManagementException, NoSuchAlgorithmException {
    HttpClientBuilder _builder = HttpClientBuilder.create()
            .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(__connectionTimeout)
                    .setSocketTimeout(__connectionTimeout).setConnectionRequestTimeout(__connectionTimeout)
                    .build());// w  w w.jav a 2s.  c o  m
    if (__socketFactory == null) {
        __socketFactory = new SSLConnectionSocketFactory(SSLContexts.custom().useSSL().build(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
    return _builder.setSSLSocketFactory(__socketFactory).build();
}

From source file:org.ow2.proactive.http.CommonHttpClientBuilder.java

public CloseableHttpClient build() {
    org.apache.http.impl.client.HttpClientBuilder internalHttpClientBuilder = createInternalHttpClientBuilder();

    if (useSystemProperties) {
        internalHttpClientBuilder.useSystemProperties();
    }// ww  w.j a  v a 2s. c  om

    if (overrideAllowAnyHostname != null) {
        if (overrideAllowAnyHostname) {
            acceptAnyHostname = true;
        } else {
            acceptAnyHostname = false;
        }
    }

    if (overrideAllowAnyCertificate != null) {
        if (overrideAllowAnyCertificate) {
            acceptAnyCertificate = true;
        } else {
            acceptAnyCertificate = false;
        }
    }

    if (acceptAnyCertificate) {
        internalHttpClientBuilder.setSslcontext(createSslContext());
    }

    if (acceptAnyHostname) {
        internalHttpClientBuilder.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }

    if (maxConnections > 0) {
        internalHttpClientBuilder.setMaxConnPerRoute(maxConnections);
        internalHttpClientBuilder.setMaxConnTotal(maxConnections);
    }

    if (requestConfig != null) {
        internalHttpClientBuilder.setDefaultRequestConfig(requestConfig);
    }

    if (!useContentCompression) {
        internalHttpClientBuilder.disableContentCompression();
    }

    return internalHttpClientBuilder.build();
}