Example usage for org.apache.http.ssl SSLContexts custom

List of usage examples for org.apache.http.ssl SSLContexts custom

Introduction

In this page you can find the example usage for org.apache.http.ssl SSLContexts custom.

Prototype

public static SSLContextBuilder custom() 

Source Link

Document

Creates custom SSL context.

Usage

From source file:cn.anthony.util.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(new File("my.keystore"),
            "nopassword".toCharArray(), new TrustSelfSignedStrategy()).build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {//from  ww w .ja v a2s. c o  m

        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:com.zhch.example.commons.http.v4_5.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom()
            .loadTrustMaterial(new File("d:\\workspace_mars\\resume_import_system\\jssecacerts"), null,
                    new TrustSelfSignedStrategy())
            .build();//from w  ww  . j a v a  2s  . co  m
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpGet httpget = new HttpGet("https://passport.zhaopin.com/org/login");

        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:com.boonya.http.async.examples.nio.client.AsyncClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream instream = new FileInputStream(new File("my.keystore"));
    try {//from w  w w.ja va 2s .  c  om
        trustStore.load(instream, "nopassword".toCharArray());
    } finally {
        instream.close();
    }
    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
            .build();
    // Allow TLSv1 protocol only
    SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(sslcontext, new String[] { "TLSv1" },
            null, SSLIOSessionStrategy.getDefaultHostnameVerifier());
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setSSLStrategy(sslSessionStrategy).build();
    try {
        httpclient.start();
        HttpGet request = new HttpGet("https://issues.apache.org/");
        Future<HttpResponse> future = httpclient.execute(request, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}

From source file:com.luqili.http.ssl.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    String sslKeyStorePath = "/mnt/data2/clientkey/370900.pfx";
    String sslKeyStorePassword = "370900";
    String sslKeyStoreType = "PKCS12"; // JKS PKCS12
    String sslTrustStore = "/mnt/data2/clientkey/PengeSoftOARoot.cer";
    String sslTrustStorePassword = "";
    String url = "https://123.57.205.217:8082/Service/UpReportInfoServiceSvr.assx/UpReportInfo";
    String content = "Token=&CityCodes=370900&CountyCodes=&DealDate=2016-06-16T00:00:00&Reportor=?&NewBusinessArea=1000.88&NewBusinessAmount=9898&NewHouseArea=5000&NewHouseAmount=8000&NewHouseCount=20&OldReportor=?&OldBusinessArea=1234.56&OldBusinessAmount=80000&OldHouseArea=12580&OldHouseAmount=99999&OldHouseCount=100";
    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom()
            .loadTrustMaterial(new File(sslKeyStorePath), sslKeyStorePassword.toCharArray(),
                    new TrustSelfSignedStrategy())
            .loadKeyMaterial(new File(sslKeyStorePath), sslKeyStorePassword.toCharArray(),
                    sslKeyStorePassword.toCharArray())
            .build();//w w  w  .j a v a  2 s.  com
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpPost httppost = new HttpPost(url);

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

        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity, "UTF-8").trim();
                if (!"True".toUpperCase().equals(result.toUpperCase())) {
                    System.out.println(result);
                }
            }

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

From source file:org.nmdp.b12s.mac.client.http.X509Config.java

public static void main(String[] args) throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, KeyManagementException, UnrecoverableKeyException {
    URL trustKeyStoreUrl = X509Config.class.getResource("/trusted.jks");

    URL clientKeyStoreUri = X509Config.class.getResource("/test-client.jks");

    SSLContext sslContext = SSLContexts.custom()
            // Configure trusted certs
            .loadTrustMaterial(trustKeyStoreUrl, "changeit".toCharArray())
            // Configure client certificate
            .loadKeyMaterial(clientKeyStoreUri, "changeit".toCharArray(), "changeit".toCharArray()).build();

    try (TextHttpClient httpClient = new TextHttpClient("https://macbeta.b12x.org/mac/api", sslContext)) {

    }/*  www  .ja  v a2  s  .c  o  m*/
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());

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

        HttpGet httpget = new HttpGet("https://macbeta.b12x.org/mac/api/codes/AA");
        System.out.println("executing request " + httpget.getRequestLine());

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

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                Charset charset = StandardCharsets.UTF_8;
                for (Header contentType : response.getHeaders("Content-Type")) {
                    System.out.println("Content-Type: " + contentType);
                    for (String part : contentType.getValue().split(";")) {
                        if (part.startsWith("charset=")) {
                            String charsetName = part.split("=")[1];
                            charset = Charset.forName(charsetName);
                        }
                    }
                }
                System.out.println("Response content length: " + entity.getContentLength());
                String content = EntityUtils.toString(entity, charset);
                System.out.println(content);
            }
            EntityUtils.consume(entity);
        }
    }
}

From source file:org.springframework.cloud.dataflow.rest.util.HttpUtils.java

/**
 * Will create a certificate-ignoring {@link SSLContext}. Please use with utmost
 * caution as it undermines security, but may be useful in certain testing or
 * development scenarios.//from   ww  w  . j a  v a2s.c o m
 *
 * @return an SSLContext that will ignore peer certificates
 */
public static SSLContext buildCertificateIgnoringSslContext() {
    try {
        return SSLContexts.custom().loadTrustMaterial((chain, authType) -> true).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        throw new IllegalStateException(
                "Unexpected exception while building the certificate-ignoring SSLContext" + ".", e);
    }
}

From source file:com.ethercamp.harmony.util.TrustSSL.java

/**
 * Allows server to connect to HTTPS sites.
 *///from www  .j  a v  a2  s .c  o  m
public static void apply() {
    // ignore https errors
    SSLContext sslcontext = null;
    try {
        sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
    } catch (Exception e) {
        e.printStackTrace();
    }

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    Unirest.setHttpClient(httpclient);
}

From source file:org.springframework.cloud.contract.wiremock.WireMockSpring.java

public static WireMockConfiguration options() {
    if (!initialized) {
        if (ClassUtils.isPresent("org.apache.http.conn.ssl.NoopHostnameVerifier", null)) {
            HttpsURLConnection.setDefaultHostnameVerifier(NoopHostnameVerifier.INSTANCE);
            try {
                HttpsURLConnection.setDefaultSSLSocketFactory(SSLContexts.custom()
                        .loadTrustMaterial(null, TrustSelfSignedStrategy.INSTANCE).build().getSocketFactory());
            } catch (Exception e) {
                Assert.fail("Cannot install custom socket factory: [" + e.getMessage() + "]");
            }/* w  w w.  j  a  v  a  2s .  c  om*/
        }
        initialized = true;
    }
    WireMockConfiguration config = new WireMockConfiguration();
    config.httpServerFactory(new SpringBootHttpServerFactory());
    return config;
}

From source file:com.consol.citrus.samples.todolist.config.SoapClientSslConfig.java

@Bean
public HttpClient httpClient() {
    try {//from   ww  w  . j  a v a  2s  .  co  m
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(new ClassPathResource("keys/citrus.jks").getFile(), "secret".toCharArray(),
                        new TrustSelfSignedStrategy())
                .build();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslcontext,
                NoopHostnameVerifier.INSTANCE);

        return HttpClients.custom().setSSLSocketFactory(sslSocketFactory)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .addInterceptorFirst(new HttpComponentsMessageSender.RemoveSoapHeadersInterceptor()).build();
    } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException
            | KeyManagementException e) {
        throw new BeanCreationException("Failed to create http client for ssl connection", e);
    }
}

From source file:com.consol.citrus.samples.todolist.config.HttpClientSslConfig.java

@Bean
public HttpClient httpClient() {
    try {//  w w  w  .ja v  a 2 s  .  c o  m
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(new ClassPathResource("keys/citrus.jks").getFile(), "secret".toCharArray(),
                        new TrustSelfSignedStrategy())
                .build();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslcontext,
                NoopHostnameVerifier.INSTANCE);

        return HttpClients.custom().setSSLSocketFactory(sslSocketFactory)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
    } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException
            | KeyManagementException e) {
        throw new BeanCreationException("Failed to create http client for ssl connection", e);
    }
}