HttpsUtils.java 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. package cn.efunbox.base.util;
  2. import org.apache.http.*;
  3. import org.apache.http.client.entity.UrlEncodedFormEntity;
  4. import org.apache.http.client.methods.HttpPost;
  5. import org.apache.http.config.Registry;
  6. import org.apache.http.config.RegistryBuilder;
  7. import org.apache.http.conn.socket.ConnectionSocketFactory;
  8. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  9. import org.apache.http.conn.ssl.NoopHostnameVerifier;
  10. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  11. import org.apache.http.conn.ssl.TrustStrategy;
  12. import org.apache.http.impl.client.CloseableHttpClient;
  13. import org.apache.http.impl.client.HttpClients;
  14. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  15. import org.apache.http.message.BasicNameValuePair;
  16. import org.apache.http.ssl.SSLContextBuilder;
  17. import org.apache.http.util.EntityUtils;
  18. import java.io.IOException;
  19. import java.security.cert.CertificateException;
  20. import java.security.cert.X509Certificate;
  21. import java.util.ArrayList;
  22. import java.util.List;
  23. import java.util.Map;
  24. public class HttpsUtils {
  25. private static final String HTTP = "http";
  26. private static final String HTTPS = "https";
  27. private static SSLConnectionSocketFactory sslsf = null;
  28. private static PoolingHttpClientConnectionManager cm = null;
  29. private static SSLContextBuilder builder = null;
  30. static {
  31. try {
  32. builder = new SSLContextBuilder();
  33. // 全部信任 不做身份鉴定
  34. builder.loadTrustMaterial(null, new TrustStrategy() {
  35. @Override
  36. public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
  37. return true;
  38. }
  39. });
  40. sslsf = new SSLConnectionSocketFactory(builder.build(), new String[] { "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2" }, null, NoopHostnameVerifier.INSTANCE);
  41. Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register(HTTP, new PlainConnectionSocketFactory()).register(HTTPS, sslsf).build();
  42. cm = new PoolingHttpClientConnectionManager(registry);
  43. cm.setMaxTotal(200);// max connection
  44. } catch (Exception e) {
  45. e.printStackTrace();
  46. }
  47. }
  48. /**
  49. * httpClient post请求
  50. *
  51. * @param url 请求url
  52. * @param header 头部信息
  53. * @param param 请求参数 form提交适用
  54. * @param entitys 请求实体 json/xml提交适用
  55. * @return 可能为空 需要处理
  56. * @throws Exception */
  57. public static String post(String url, Map<String, String> header, Map<String, String> param, HttpEntity entity) throws Exception {
  58. String result = "";
  59. CloseableHttpClient httpClient = null;
  60. try {
  61. httpClient = getHttpClient();
  62. HttpPost httpPost = new HttpPost(url);
  63. // 设置头信息
  64. if (null != header && header.size() > 0) {
  65. for (Map.Entry<String, String> entry : header.entrySet()) {
  66. httpPost.addHeader(entry.getKey(), entry.getValue());
  67. }
  68. }
  69. // 设置请求参数
  70. if (null != param && param.size() > 0) {
  71. List<NameValuePair> formparams = new ArrayList<NameValuePair>();
  72. for (Map.Entry<String, String> entry : param.entrySet()) {
  73. // 给参数赋值
  74. formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  75. }
  76. UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
  77. httpPost.setEntity(urlEncodedFormEntity);
  78. }
  79. // 设置实体 优先级高
  80. if (entity != null) {
  81. httpPost.setEntity(entity);
  82. }
  83. HttpResponse httpResponse = httpClient.execute(httpPost);
  84. int statusCode = httpResponse.getStatusLine().getStatusCode();
  85. if (statusCode == HttpStatus.SC_OK) {
  86. HttpEntity resEntity = httpResponse.getEntity();
  87. result = EntityUtils.toString(resEntity);
  88. } else {
  89. readHttpResponse(httpResponse);
  90. }
  91. } catch (Exception e) {
  92. throw e;
  93. } finally {
  94. if (httpClient != null) {
  95. httpClient.close();
  96. }
  97. }
  98. return result;
  99. }
  100. public static CloseableHttpClient getHttpClient() throws Exception {
  101. CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm).setConnectionManagerShared(true).build();
  102. return httpClient;
  103. }
  104. public static String readHttpResponse(HttpResponse httpResponse) throws ParseException, IOException {
  105. StringBuilder builder = new StringBuilder();
  106. // 获取响应消息实体
  107. HttpEntity entity = httpResponse.getEntity();
  108. // 响应状态
  109. builder.append("status:" + httpResponse.getStatusLine());
  110. builder.append("headers:");
  111. HeaderIterator iterator = httpResponse.headerIterator();
  112. while (iterator.hasNext()) {
  113. builder.append("\t" + iterator.next());
  114. }
  115. // 判断响应实体是否为空
  116. if (entity != null) {
  117. String responseString = EntityUtils.toString(entity);
  118. builder.append("response length:" + responseString.length());
  119. builder.append("response content:" + responseString.replace("\r\n", ""));
  120. }
  121. System.out.println("rsponse:"+builder);
  122. return builder.toString();
  123. }
  124. }