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

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

Introduction

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

Prototype

public SSLConnectionSocketFactory(final javax.net.ssl.SSLSocketFactory socketfactory,
            final String[] supportedProtocols, final String[] supportedCipherSuites,
            final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

From source file:com.renren.ntc.sg.util.wxpay.https.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(
            new File("/Users/allenz/Downloads/wx_cert/apiclient_cert.p12"));
    try {//w ww.ja  v  a  2 s  .  com
        keyStore.load(instream, Constants.mch_id.toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, Constants.mch_id.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 post = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers");
        System.out.println("executing request" + post.getRequestLine());

        String openid = "oQfDLjmZD7Lgynv6vuoBlWXUY_ic";
        String nonce_str = Sha1Util.getNonceStr();
        String orderId = SUtils.getOrderId();
        String re_user_name = "?";
        String amount = "1";
        String desc = "";
        String spbill_create_ip = "123.56.102.224";

        String txt = TXT.replace("{mch_appid}", Constants.mch_appid);
        txt = txt.replace("{mchid}", Constants.mch_id);
        txt = txt.replace("{openid}", openid);
        txt = txt.replace("{nonce_str}", nonce_str);
        txt = txt.replace("{partner_trade_no}", orderId);
        txt = txt.replace("{check_name}", "FORCE_CHECK");
        txt = txt.replace("{re_user_name}", re_user_name);
        txt = txt.replace("{amount}", amount);
        txt = txt.replace("{desc}", desc);
        txt = txt.replace("{spbill_create_ip}", spbill_create_ip);

        SortedMap<String, String> map = new TreeMap<String, String>();
        map.put("mch_appid", Constants.mch_appid);
        map.put("mchid", Constants.mch_id);
        map.put("openid", openid);
        map.put("nonce_str", nonce_str);
        map.put("partner_trade_no", orderId);
        //FORCE_CHECK| OPTION_CHECK | NO_CHECK
        map.put("check_name", "OPTION_CHECK");
        map.put("re_user_name", re_user_name);
        map.put("amount", amount);
        map.put("desc", desc);
        map.put("spbill_create_ip", spbill_create_ip);

        String sign = SUtils.createSign(map).toUpperCase();
        txt = txt.replace("{sign}", sign);

        post.setEntity(new StringEntity(txt, "utf-8"));

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

            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                StringBuffer sb = new StringBuffer();
                while ((text = bufferedReader.readLine()) != null) {
                    sb.append(text);
                }
                String resp = sb.toString();
                LoggerUtils.getInstance().log(String.format("req %s rec %s", txt, resp));
                if (isOk(resp)) {

                    String payment_no = getValue(resp, "payment_no");
                    LoggerUtils.getInstance()
                            .log(String.format("order %s pay OK   payment_no %s", orderId, payment_no));
                }

            }
            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)) {

    }/* w w  w . j a  va  2s.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:com.hy.utils.pay.wx.ClientCustomSSL.java

public static void test() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("D:/10016225.p12"));
    try {/* w  w  w .  j  a va 2s  . c o m*/
        keyStore.load(instream, "10016225".toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "10016225".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 {

        HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");

        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());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                }

            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.mirth.connect.connectors.ws.DefaultWebServiceConfiguration.java

@Override
public void configureConnectorDeploy(Connector connector) throws Exception {
    if (connector instanceof WebServiceDispatcher) {
        sslContext = SSLContexts.createSystemDefault();
        enabledProtocols = MirthSSLUtil/*from  w  ww.j a  va 2s.c om*/
                .getEnabledHttpsProtocols(configurationController.getHttpsClientProtocols());
        enabledCipherSuites = MirthSSLUtil
                .getEnabledHttpsCipherSuites(configurationController.getHttpsCipherSuites());
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                enabledProtocols, enabledCipherSuites, NoopHostnameVerifier.INSTANCE);
        ((WebServiceDispatcher) connector).getSocketFactoryRegistry().register("https",
                sslConnectionSocketFactory);
    }
}

From source file:com.deying.util.weixin.ClientCustomSSL.java

public static String doRefund(String url, String data) throws Exception {
    System.out.println("111111111111111111111111111111111111111111111118 ");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("E:/apiclient_cert.p12"));//P12
    try {//from  w  w  w .ja v a  2 s .  c  o  m
        keyStore.load(instream, "1233374102".toCharArray());//?..MCHID
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "1233374102".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 httpost = new HttpPost(url); // ??
        httpost.addHeader("Connection", "keep-alive");
        httpost.addHeader("Accept", "*/*");
        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpost.addHeader("Host", "api.mch.weixin.qq.com");
        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        httpost.addHeader("Cache-Control", "max-age=0");
        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
        httpost.setEntity(new StringEntity(data, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpost);
        try {
            HttpEntity entity = response.getEntity();

            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            EntityUtils.consume(entity);
            return jsonStr;
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.bbc.util.ClientCustomSSL.java

public static String clientCustomSLL(String mchid, String path, String data) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");

    System.out.println("?...");
    FileInputStream instream = new FileInputStream(new File("/payment/apiclient_cert.p12"));
    try {//from ww w  .j  a  va2  s  .  c  o m
        keyStore.load(instream, mchid.toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mchid.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 httpost = new HttpPost(path);
        httpost.addHeader("Connection", "keep-alive");
        httpost.addHeader("Accept", "*/*");
        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpost.addHeader("Host", "api.mch.weixin.qq.com");
        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        httpost.addHeader("Cache-Control", "max-age=0");
        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");

        httpost.setEntity(new StringEntity(data, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpost);
        try {
            HttpEntity entity = response.getEntity();
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                StringBuffer sb = new StringBuffer("");
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                    sb.append(text);
                }
                return sb.toString();

            }
            EntityUtils.consume(entity);
            return "";
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.jeecms.common.web.ClientCustomSSL.java

public static String getInSsl(String url, File pkcFile, String storeId, String params, String contentType)
        throws Exception {
    String text = "";
    // ???PKCS12//from   www.  ja  v  a 2 s  . co m
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    // ?PKCS12?
    FileInputStream instream = new FileInputStream(pkcFile);
    try {
        // PKCS12?(ID)
        keyStore.load(instream, storeId.toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, storeId.toCharArray()).build();
    // Allow TLSv1 protocol only
    // TLS 
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    // httpclientSSLSocketFactory
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {
        HttpPost post = new HttpPost(url);
        StringEntity s = new StringEntity(params, "utf-8");
        if (StringUtils.isBlank(contentType)) {
            s.setContentType("application/xml");
        }
        s.setContentType(contentType);
        post.setEntity(s);
        HttpResponse res = httpclient.execute(post);
        HttpEntity entity = res.getEntity();
        text = EntityUtils.toString(entity, "utf-8");
    } finally {
        httpclient.close();
    }
    return text;
}

From source file:estacionamento.util.HTTPUtil.java

/**
 *
 * @return/*from  w w w  . ja v a2s  .  com*/
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws CertificateException {

        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws CertificateException {

        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, trustAllCerts, new SecureRandom());

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

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

    return httpclient;
}

From source file:com.nieyue.weixin.ssl.ClientCustomSSL.java

/**
 * ?//from   w w  w .j a v a 2 s  .  c  om
 * @return
 * @throws Exception
 */
public static CloseableHttpClient getCloseableHttpClient() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(
            new File(ClientCustomSSL.class.getResource("").getPath() + "apiclient_cert.p12"));
    //?
    //FileInputStream instream = new FileInputStream("src/com/nieyue/weixin/ssl/apiclient_cert.p12");
    try {
        keyStore.load(instream, ThirdParty.GetValueByKey(ThirdParty.WEIXIN_YAYAO_MCH_ID).toCharArray());
    } finally {
        instream.close();
    }
    // Trust own CA and all self-signed certs
    @SuppressWarnings("deprecation")
    SSLContext sslcontext = SSLContexts.custom()
            .loadKeyMaterial(keyStore, ThirdParty.GetValueByKey(ThirdParty.WEIXIN_YAYAO_MCH_ID).toCharArray())
            .build();
    // Allow TLSv1 protocol only
    @SuppressWarnings("deprecation")
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    return httpclient;
}

From source file:com.simple.weixin.refund.ClientCustomSSL.java

public static String doRefund(String password, String keyStrore, String url, String data) throws Exception {
    /**//from  ww w  .j  a  v  a2  s .  com
     * ?PKCS12? ?-- API 
     */

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File(keyStrore));//P12
    try {
        /**
         * ?
         * */
        keyStore.load(instream, password.toCharArray());//?..MCHID
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    /**
    * ?
    * */
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, password.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 httpost = new HttpPost(url); // ??
        httpost.addHeader("Connection", "keep-alive");
        httpost.addHeader("Accept", "*/*");
        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpost.addHeader("Host", "api.mch.weixin.qq.com");
        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        httpost.addHeader("Cache-Control", "max-age=0");
        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
        httpost.setEntity(new StringEntity(data, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpost);
        try {
            HttpEntity entity = response.getEntity();

            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            EntityUtils.consume(entity);
            return jsonStr;
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}