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

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

Introduction

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

Prototype

X509HostnameVerifier BROWSER_COMPATIBLE_HOSTNAME_VERIFIER

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

Click Source Link

Usage

From source file:com.ksc.http.apache.client.impl.ApacheConnectionManagerFactory.java

@SuppressWarnings("deprecation")
private HostnameVerifier getHostNameVerifier(HttpClientSettings options) {
    return options.useBrowserCompatibleHostNameVerifier()
            ? SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER
            : SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;
}

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

private void createClient() {

    try {/*from  w  w  w .  ja v  a2  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:br.com.intercomex.ws.GnreConfigUF.java

/**
 * This is a sample web service operation
 *//*from   ww  w  .j a  v a 2 s  . c om*/
@WebMethod(operationName = "consultar")
public String consultar(@WebParam(name = "gnreDadosMsg") TConsultaConfigUf gnreDadosMsg) {
    String retorno = null;
    loadConfig();
    try {
        //<TConsultaConfigUf xmlns=\"http://www.gnre.pe.gov.br\"><ambiente>1</ambiente><uf>MG</uf><receita>100048</receita></TConsultaConfigUf>
        String XML_DATA = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:gnr=\"http://www.gnre.pe.gov.br/webservice/GnreConfigUF\">"
                + "<soap:Header><gnr:gnreCabecMsg><gnr:versaoDados>1.00</gnr:versaoDados></gnr:gnreCabecMsg></soap:Header>"
                + " <soap:Body><gnr:gnreDadosMsg>" + gnreDadosMsg
                + "</gnr:gnreDadosMsg></soap:Body></soap:Envelope>";
        System.out.println("PARAMETRO envio ==== " + gnreDadosMsg);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader(new BasicHeader("Content-Type", "application/soap+xml;charset=UTF-8"));
        httpPost.setHeader(new BasicHeader("SOAPAction", action));
        StringEntity s = new StringEntity(XML_DATA, "UTF-8");
        httpPost.setEntity(s);
        FileInputStream instream = null;
        FileInputStream instreamTrust = null;
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        instream = new FileInputStream(new File(caminhoDoCertificadoDoCliente));
        keyStore.load(instream, senhaDoCertificadoDoCliente.toCharArray());

        KeyStore trustStore = KeyStore.getInstance("JKS");
        instreamTrust = new FileInputStream(new File(arquivoCacertsGeradoParaCadaEstado));
        trustStore.load(instreamTrust, senhaDoCertificadoDoCliente.toCharArray());

        SSLContextBuilder builder = SSLContexts.custom().loadTrustMaterial(trustStore);
        builder.loadKeyMaterial(keyStore, senhaDoCertificadoDoCliente.toCharArray());
        SSLContext sslcontext = builder.build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclientSLL = HttpClients.custom().setSSLSocketFactory(sslsf).build();

        System.out.println("executing request" + httpPost.getRequestLine());
        HttpResponse response = httpclientSLL.execute(httpPost);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
            retorno = EntityUtils.toString(response.getEntity());
            System.out.println(retorno);

        }
        if (entity != null) {
            entity.consumeContent();
        }
        httpclient.getConnectionManager().shutdown();

    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (CertificateException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnrecoverableKeyException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    }

    return retorno;
}

From source file:org.openscore.content.httpclient.build.conn.SSLConnectionSocketFactoryBuilder.java

public SSLConnectionSocketFactory build() {
    if (!"true".equalsIgnoreCase(trustAllRootsStr) && !"false".equalsIgnoreCase(trustAllRootsStr)) {
        throw new IllegalArgumentException("'trustAllRoots' can only be 'true' or 'false'");
    }//  w ww  .  ja  v a2 s . c  om
    boolean trustAllRoots = Boolean.parseBoolean(trustAllRootsStr);

    SSLContextBuilder sslContextBuilder = SSLContexts.custom();
    if (!trustAllRoots) {
        boolean useClientCert = !StringUtils.isEmpty(keystore);
        //validate SSL certificates sent by the server
        boolean useTrustCert = !StringUtils.isEmpty(trustKeystore);

        String javaKeystore = System.getProperty("java.home") + "/lib/security/cacerts";
        boolean storeExists = new File(javaKeystore).exists();

        if (!useClientCert && storeExists) {
            keystore = "file:" + javaKeystore;
            keystorePassword = (StringUtils.isEmpty(keystorePassword)) ? "changeit" : keystorePassword;
            useClientCert = true;
        } else if (useClientCert && !keystore.startsWith("http")) {
            keystore = "file:" + keystore;
        }

        if (!useTrustCert && storeExists) {
            trustKeystore = "file:" + javaKeystore;
            trustPassword = (StringUtils.isEmpty(trustPassword)) ? "changeit" : trustPassword;
            useTrustCert = true;
        } else if (useTrustCert && !trustKeystore.startsWith("http")) {
            trustKeystore = "file:" + trustKeystore;
        }
        createTrustKeystore(sslContextBuilder, useTrustCert);
        //todo client key authentication should not depend on 'trustAllRoots'
        createKeystore(sslContextBuilder, useClientCert);
    } else {
        try {
            //need to override isTrusted() method to accept CA certs because the Apache HTTP Client ver.4.3 will only accepts self-signed certificates
            sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            });
        } catch (Exception e) {
            throw new IllegalArgumentException(e.getMessage() + ". " + TRUST_ALL_ROOTS_ERROR + trustAllRoots,
                    e);
        }
    }

    sslContextBuilder.useSSL();
    sslContextBuilder.useTLS();

    SSLConnectionSocketFactory sslsf;
    try {
        String x509HostnameVerifierStr = x509HostnameVerifier.toLowerCase();
        X509HostnameVerifier x509HostnameVerifier = null;
        switch (x509HostnameVerifierStr) {
        case "strict":
            x509HostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;
            break;
        case "browser_compatible":
            x509HostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
            break;
        case "allow_all":
            x509HostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            break;
        default:
            x509HostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;
        }

        sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), x509HostnameVerifier);
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage() + ". " + SSL_CONNECTION_ERROR, e);
    }
    return sslsf;
}

From source file:com.enioka.jqm.tools.JettyTest.java

@Test
public void testSslClientCert() throws Exception {
    Helpers.setSingleParam("enableWsApiSsl", "true", em);
    Helpers.setSingleParam("disableWsApi", "false", em);
    Helpers.setSingleParam("enableWsApiAuth", "false", em);

    addAndStartEngine();//w w w .  ja  va 2 s . c  o  m

    // Launch a job so as to be able to query its status later
    CreationTools.createJobDef(null, true, "App", null, "jqm-tests/jqm-test-datetimemaven/target/test.jar",
            TestHelpers.qVip, 42, "MarsuApplication", null, "Franquin", "ModuleMachin", "other", "other", true,
            em);
    JobRequest j = new JobRequest("MarsuApplication", "TestUser");
    int i = JqmClientFactory.getClient().enqueue(j);
    TestHelpers.waitFor(1, 10000, em);

    // Server auth against trusted CA root certificate
    KeyStore trustStore = KeyStore.getInstance("JKS");
    FileInputStream instream = new FileInputStream(new File("./conf/trusted.jks"));
    try {
        trustStore.load(instream, "SuperPassword".toCharArray());
    } finally {
        instream.close();
    }

    // Client auth
    JpaCa.prepareClientStore(em, "CN=testuser", "./conf/client.pfx", "SuperPassword", "client-cert",
            "./conf/client.cer");
    KeyStore clientStore = KeyStore.getInstance("PKCS12");
    instream = new FileInputStream(new File("./conf/client.pfx"));
    try {
        clientStore.load(instream, "SuperPassword".toCharArray());
    } finally {
        instream.close();
    }

    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore)
            .loadKeyMaterial(clientStore, "SuperPassword".toCharArray()).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    CloseableHttpClient cl = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    int port = em.createQuery("SELECT q.port FROM Node q WHERE q.id = :i", Integer.class)
            .setParameter("i", TestHelpers.node.getId()).getSingleResult();
    HttpUriRequest rq = new HttpGet(
            "https://" + TestHelpers.node.getDns() + ":" + port + "/ws/simple/status?id=" + i);
    CloseableHttpResponse rs = cl.execute(rq);
    Assert.assertEquals(200, rs.getStatusLine().getStatusCode());

    rs.close();
    cl.close();
}

From source file:common.rest.client.transport.HttpClientSSLKeyStore.java

/**
 * Constructs the {@link org.apache.http.conn.socket.ConnectionSocketFactory} according to the options specified during the
 * construction time. The returned instance can be used to register an <b><tt>https</tt></b>
 * sheme in the {@link org.apache.http.conn.socket.ConnectionSocketFactory} while costructing an Apache HTTP client.
 *
 * @return <tt>SSLSocketFactory</tt> instance
 *///  w  w  w  .  jav a  2s. c  o m
public LayeredConnectionSocketFactory getSocketFactory() {

    // @formatter:off
    final X509HostnameVerifier hostnameVerifier = m_disableHostnameVerifier
            ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
            : SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
    // @formatter:on
    try {
        SSLContextBuilder sslContextBuilder = SSLContexts.custom();
        if (m_keyStore != null) {
            // this key store must contain the key/cert of the client
            sslContextBuilder.loadKeyMaterial(m_keyStore, m_keyStorePassword.toCharArray());
        }
        if (m_trustStore != null) {
            // this key store must contain the certs needed and trusted to verify the servers cert
            sslContextBuilder.loadTrustMaterial(m_trustStore);
        }

        return new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
    } catch (Exception e) {
        throw new IllegalStateException("Failed to create SSL Socket Factory", e);
    }
}

From source file:io.cloudslang.content.httpclient.build.conn.SSLConnectionSocketFactoryBuilder.java

public SSLConnectionSocketFactory build() {
    if (!"true".equalsIgnoreCase(trustAllRootsStr) && !"false".equalsIgnoreCase(trustAllRootsStr)) {
        throw new IllegalArgumentException("'trustAllRoots' can only be 'true' or 'false'");
    }//from  w  w w .j av  a  2s  .c  om
    boolean trustAllRoots = Boolean.parseBoolean(trustAllRootsStr);

    SSLContextBuilder sslContextBuilder = SSLContexts.custom();
    if (!trustAllRoots) {
        boolean useClientCert = !StringUtils.isEmpty(keystore);
        //validate SSL certificates sent by the server
        boolean useTrustCert = !StringUtils.isEmpty(trustKeystore);

        String javaKeystore = System.getProperty("java.home") + "/lib/security/cacerts";
        boolean storeExists = new File(javaKeystore).exists();

        if (!useClientCert && storeExists) {
            keystore = "file:" + javaKeystore;
            keystorePassword = (StringUtils.isEmpty(keystorePassword)) ? "changeit" : keystorePassword;
            useClientCert = true;
        } else if (useClientCert && !keystore.startsWith("http")) {
            keystore = "file:" + keystore;
        }

        if (!useTrustCert && storeExists) {
            trustKeystore = "file:" + javaKeystore;
            trustPassword = (StringUtils.isEmpty(trustPassword)) ? "changeit" : trustPassword;
            useTrustCert = true;
        } else if (useTrustCert && !trustKeystore.startsWith("http")) {
            trustKeystore = "file:" + trustKeystore;
        }
        createTrustKeystore(sslContextBuilder, useTrustCert);
        //todo client key authentication should not depend on 'trustAllRoots'
        createKeystore(sslContextBuilder, useClientCert);
    } else {
        try {
            //need to override isTrusted() method to accept CA certs because the Apache HTTP Client ver.4.3 will only accepts self-signed certificates
            sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            });
        } catch (Exception e) {
            throw new IllegalArgumentException(e.getMessage() + ". " + TRUST_ALL_ROOTS_ERROR + trustAllRoots,
                    e);
        }
    }

    sslContextBuilder.useSSL();
    sslContextBuilder.useTLS();

    SSLConnectionSocketFactory sslsf;
    try {
        String x509HostnameVerifierStr = x509HostnameVerifierInputValue.toLowerCase();
        X509HostnameVerifier x509HostnameVerifier;
        switch (x509HostnameVerifierStr) {
        case "strict":
            x509HostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;
            break;
        case "browser_compatible":
            x509HostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
            break;
        case "allow_all":
            x509HostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            break;
        default:
            throw new IllegalArgumentException("Invalid value '" + x509HostnameVerifierInputValue
                    + "' for input 'x509HostnameVerifier'. Valid values: 'strict','browser_compatible','allow_all'.");
        }
        // Allow SSLv3, TLSv1, TLSv1.1 and TLSv1.2 protocols only. Client-server communication starts with TLSv1.2 and fallbacks to SSLv3 if needed.
        sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), SUPPORTED_PROTOCOLS, null,
                x509HostnameVerifier);
    } catch (Exception e) {
        if (e instanceof IllegalArgumentException) {
            throw new IllegalArgumentException(e.getMessage());
        }
        throw new RuntimeException(e.getMessage() + ". " + SSL_CONNECTION_ERROR, e);
    }
    return sslsf;
}

From source file:br.com.intercomex.ws.GnreResultadoLote.java

/**
 * This is a sample web service operation
 *//*from  w  ww  .ja v a 2  s . c  o  m*/
//@WebMethod(operationName = "consultarLote")
private TResultLoteGNRE consultarLote(@WebParam(name = "gnreDadosMsgLote") TConsLote_GNRE gnreDadosMsg) {
    TResultLoteGNRE retorno = null;
    loadConfig();
    try {
        //<TConsLote_GNRE xmlns="http://www.gnre.pe.gov.br"><ambiente>1</ambiente><numeroRecibo>2012314940</numeroRecibo></TConsLote_GNRE>
        String XML_DATA = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:gnr=\"http://www.gnre.pe.gov.br/webservice/GnreResultadoLote\">"
                + "<soap:Header><gnr:gnreCabecMsg><gnr:versaoDados>1.00</gnr:versaoDados></gnr:gnreCabecMsg></soap:Header>"
                + " <soap:Body><gnr:gnreDadosMsg>" + gnreDadosMsg
                + "</gnr:gnreDadosMsg></soap:Body></soap:Envelope>";

        System.out.println("PARAMETRO envio ==== " + gnreDadosMsg);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader(new BasicHeader("Content-Type", "application/soap+xml;charset=UTF-8"));
        httpPost.setHeader(new BasicHeader("SOAPAction", action));
        StringEntity s = new StringEntity(XML_DATA, "UTF-8");
        httpPost.setEntity(s);
        FileInputStream instream = null;
        FileInputStream instreamTrust = null;
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        instream = new FileInputStream(new File(caminhoDoCertificadoDoCliente));
        keyStore.load(instream, senhaDoCertificadoDoCliente.toCharArray());

        KeyStore trustStore = KeyStore.getInstance("JKS");
        instreamTrust = new FileInputStream(new File(arquivoCacertsGeradoParaCadaEstado));
        trustStore.load(instreamTrust, senhaDoCertificadoDoCliente.toCharArray());

        SSLContextBuilder builder = SSLContexts.custom().loadTrustMaterial(trustStore);
        builder.loadKeyMaterial(keyStore, senhaDoCertificadoDoCliente.toCharArray());
        SSLContext sslcontext = builder.build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclientSLL = HttpClients.custom().setSSLSocketFactory(sslsf).build();

        System.out.println("executing request" + httpPost.getRequestLine());
        System.out.println("Conteudo envio ==== " + XML_DATA);
        HttpResponse response = httpclientSLL.execute(httpPost);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
            String str = EntityUtils.toString(entity);
            System.out.println(str);
            XmlUtil util = new XmlUtil();
            retorno = util.getTResultLoteGNRE(str);

        }
        if (entity != null) {
            entity.consumeContent();
        }
        httpclient.getConnectionManager().shutdown();

    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (CertificateException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnrecoverableKeyException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    }

    return retorno;
}

From source file:cn.mrdear.pay.util.WebUtils.java

/**
 * ?/*from   www . j a v a2 s .co m*/
 * @param certPath ?
 * @param passwd  ??
 * @param uri ?
 * @param entity xml
 * @return 
 */
public static String post(String certPath, String passwd, String uri, InputStreamEntity entity)
        throws Exception {
    String result = null;
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File(certPath));
    try {
        keyStore.load(instream, passwd.toCharArray());
    } finally {
        instream.close();
    }
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, passwd.toCharArray()).build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {
        HttpPost httpPost = new HttpPost(uri);
        entity.setContentEncoding("UTF-8");
        httpPost.setEntity(entity);
        CloseableHttpResponse httpResponse = httpclient.execute(httpPost);
        result = consumeResponse(httpResponse);
    } finally {
        httpclient.close();
    }
    return result;
}