微信支付---申请退款的https双向认证demo

来源:互联网 发布:自然语言和c语言 编辑:程序博客网 时间:2024/05/15 20:59
/**
* https双向签名认证,用于支付申请退款

* */
    public static String payHttps(String url,String data) throws Exception {
    //商户id
    String MCH_ID = PropUtil.getPropertyValue("wx.sz.mchid", "").replace("\"","");
    //指定读取证书格式为PKCS12
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    String path =PropUtil.getPropertyValue("wx.sz.certificate.path", "D:/apiclient_cert.p12").replace("\"","");
    //读取本机存放的PKCS12证书文件
    FileInputStream instream = new FileInputStream(new File(path));
    try {
    //指定PKCS12的密码(商户ID)
   
    keyStore.load(instream, MCH_ID.toCharArray());
    } finally {
    instream.close();
    }
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, MCH_ID.toCharArray()).build();
    //指定TLS版本
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
    sslcontext,new String[] { "TLSv1" },null,
    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    //设置httpclient的SSLSocketFactory
    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();
        }
    }
0 0