ClientCustomSSL.java 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package cn.efunbox.manage.base.util;
  2. import org.apache.http.HttpEntity;
  3. import org.apache.http.client.methods.CloseableHttpResponse;
  4. import org.apache.http.client.methods.HttpPost;
  5. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  6. import org.apache.http.conn.ssl.SSLContexts;
  7. import org.apache.http.entity.StringEntity;
  8. import org.apache.http.impl.client.CloseableHttpClient;
  9. import org.apache.http.impl.client.HttpClients;
  10. import org.apache.http.util.EntityUtils;
  11. import org.springframework.util.ResourceUtils;
  12. import javax.net.ssl.SSLContext;
  13. import java.io.File;
  14. import java.io.FileInputStream;
  15. import java.security.KeyStore;
  16. /**
  17. * 退款认证
  18. * 创建者 tomas
  19. * 创建时间 2017年7月31日
  20. *
  21. */
  22. public class ClientCustomSSL {
  23. public static String httpsRequest(String url,String data) throws Exception {
  24. /**
  25. * 注意PKCS12证书 是从微信商户平台-》账户设置-》 API安全 中下载的
  26. */
  27. KeyStore keyStore = KeyStore.getInstance("PKCS12");
  28. File certfile = ResourceUtils.getFile(ConfigUtil.CERT_PATH);
  29. FileInputStream instream = new FileInputStream(certfile);
  30. try {
  31. keyStore.load(instream, ConfigUtil.MCH_ID.toCharArray());
  32. } finally {
  33. instream.close();
  34. }
  35. SSLContext sslcontext = SSLContexts.custom()
  36. .loadKeyMaterial(keyStore, ConfigUtil.MCH_ID.toCharArray())
  37. .build();
  38. SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
  39. sslcontext,
  40. new String[] { "TLSv1" },
  41. null,
  42. SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
  43. CloseableHttpClient httpclient = HttpClients.custom()
  44. .setSSLSocketFactory(sslsf)
  45. .build();
  46. try {
  47. HttpPost httpost = new HttpPost(url);
  48. httpost.setEntity(new StringEntity(data, "UTF-8"));
  49. CloseableHttpResponse response = httpclient.execute(httpost);
  50. try {
  51. HttpEntity entity = response.getEntity();
  52. String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
  53. EntityUtils.consume(entity);
  54. return jsonStr;
  55. } finally {
  56. response.close();
  57. }
  58. } finally {
  59. httpclient.close();
  60. }
  61. }
  62. }