wuzeyu
2024-05-06 cd45cee236780a8e02244d8d8a916088ca002d3d
pipIrr-platform/pipIrr-common/src/main/java/com/dy/common/util/HttpUtils.java
@@ -1,11 +1,12 @@
package com.dy.common.util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@@ -17,15 +18,25 @@
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
@@ -36,18 +47,18 @@
   /**
    * get
    * 
    * @param host
    * @param path
    * @param headers
    * @param querys
    * @return
    * @throws Exception
    * @param host 服务端URI
    * @param path 请求路径
    * @param headers 请求头
    * @param params 请求参数
    * @return HttpResponse响应
    * @throws Exception 异常
    */
   public static HttpResponse doGet(String host, String path, Map<String, String> headers,
         Map<String, String> querys) throws Exception {
         Map<String, String> params) throws Exception{
      HttpClient httpClient = wrapClient(host);
      HttpGet request = new HttpGet(buildUrl(host, path, querys));
      HttpGet request = new HttpGet(buildUrl(host, path, params));
      if(headers != null){
         for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
@@ -59,29 +70,29 @@
   /**
    * post form
    *
    * @param host
    * @param path
    * @param headers
    * @param querys
    * @param bodys
    * @return
    * @throws Exception
    *
    * @param host 服务端URI
    * @param path 请求路径
    * @param headers 请求头
    * @param params 请求参数
    * @param bodies 请求体
    * @return HttpResponse响应
    * @throws Exception 异常
    */
   public static HttpResponse doPost(String host, String path, Map<String, String> headers,
         Map<String, String> querys, Map<String, String> bodys) throws Exception {
         Map<String, String> params, Map<String, String> bodies) throws Exception {
      HttpClient httpClient = wrapClient(host);
      HttpPost request = new HttpPost(buildUrl(host, path, querys));
      HttpPost request = new HttpPost(buildUrl(host, path, params));
      for (Map.Entry<String, String> e : headers.entrySet()) {
         request.addHeader(e.getKey(), e.getValue());
      }
      if (bodys != null) {
         List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
      if (bodies != null) {
         List<NameValuePair> nameValuePairList = new ArrayList<>();
         for (String key : bodys.keySet()) {
            nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
         for (String key : bodies.keySet()) {
            nameValuePairList.add(new BasicNameValuePair(key, bodies.get(key)));
         }
         UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
         formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
@@ -93,20 +104,20 @@
   /**
    * Post String
    *
    * @param host
    * @param path
    * @param headers
    * @param querys
    * @param body
    * @return
    * @throws Exception
    *
    * @param host 服务端URI
    * @param path 请求路径
    * @param headers 请求头
    * @param params 请求参数
    * @param body 请求体
    * @return HttpResponse响应
    * @throws Exception 异常
    */
   public static HttpResponse doPost(String host, String path, Map<String, String> headers,
         Map<String, String> querys, String body) throws Exception {
         Map<String, String> params, String body) throws Exception {
      HttpClient httpClient = wrapClient(host);
      HttpPost request = new HttpPost(buildUrl(host, path, querys));
      HttpPost request = new HttpPost(buildUrl(host, path, params));
      for (Map.Entry<String, String> e : headers.entrySet()) {
         request.addHeader(e.getKey(), e.getValue());
      }
@@ -120,20 +131,20 @@
   /**
    * Post stream
    *
    * @param host
    * @param path
    * @param headers
    * @param querys
    * @param body
    * @return
    * @throws Exception
    *
    * @param host 服务端URI
    * @param path 请求路径
    * @param headers 请求头
    * @param params 请求参数
    * @param body 请求体
    * @return HttpResponse响应
    * @throws Exception 异常
    */
   public static HttpResponse doPost(String host, String path, Map<String, String> headers,
         Map<String, String> querys, byte[] body) throws Exception {
         Map<String, String> params, byte[] body) throws Exception {
      HttpClient httpClient = wrapClient(host);
      HttpPost request = new HttpPost(buildUrl(host, path, querys));
      HttpPost request = new HttpPost(buildUrl(host, path, params));
      if(headers != null){
         for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
@@ -149,20 +160,20 @@
   /**
    * Put String
    *
    * @param host
    * @param path
    * @param headers
    * @param querys
    * @param body
    * @return
    * @throws Exception
    *
    * @param host 服务端URI
    * @param path 请求路径
    * @param headers 请求头
    * @param params 请求参数
    * @param body 请求体
    * @return HttpResponse响应
    * @throws Exception 异常
    */
   public static HttpResponse doPut(String host, String path, Map<String, String> headers,
         Map<String, String> querys, String body) throws Exception {
         Map<String, String> params, String body) throws Exception {
      HttpClient httpClient = wrapClient(host);
      HttpPut request = new HttpPut(buildUrl(host, path, querys));
      HttpPut request = new HttpPut(buildUrl(host, path, params));
      for (Map.Entry<String, String> e : headers.entrySet()) {
         request.addHeader(e.getKey(), e.getValue());
      }
@@ -176,20 +187,20 @@
   /**
    * Put stream
    *
    * @param host
    * @param path
    * @param headers
    * @param querys
    * @param body
    * @return
    * @throws Exception
    *
    * @param host 服务端URI
    * @param path 请求路径
    * @param headers 请求头
    * @param params 请求参数
    * @param body 请求体
    * @return HttpResponse响应
    * @throws Exception 异常
    */
   public static HttpResponse doPut(String host, String path, Map<String, String> headers,
         Map<String, String> querys, byte[] body) throws Exception {
         Map<String, String> params, byte[] body) throws Exception {
      HttpClient httpClient = wrapClient(host);
      HttpPut request = new HttpPut(buildUrl(host, path, querys));
      HttpPut request = new HttpPut(buildUrl(host, path, params));
      for (Map.Entry<String, String> e : headers.entrySet()) {
         request.addHeader(e.getKey(), e.getValue());
      }
@@ -203,19 +214,19 @@
   /**
    * Delete
    *
    * @param host
    * @param path
    * @param headers
    * @param querys
    * @return
    * @throws Exception
    *
    * @param host 服务端URI
    * @param path 请求路径
    * @param headers 请求头
    * @param params 请求参数
    * @return HttpResponse响应
    * @throws Exception 异常
    */
   public static HttpResponse doDelete(String host, String path, Map<String, String> headers,
         Map<String, String> querys) throws Exception {
         Map<String, String> params) throws Exception {
      HttpClient httpClient = wrapClient(host);
      HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
      HttpDelete request = new HttpDelete(buildUrl(host, path, params));
      for (Map.Entry<String, String> e : headers.entrySet()) {
         request.addHeader(e.getKey(), e.getValue());
      }
@@ -223,16 +234,15 @@
      return httpClient.execute(request);
   }
   private static String buildUrl(String host, String path, Map<String, String> querys)
         throws UnsupportedEncodingException {
   private static String buildUrl(String host, String path, Map<String, String> params) {
      StringBuilder sbUrl = new StringBuilder();
      sbUrl.append(host);
      if (!StringUtils.isBlank(path)) {
         sbUrl.append(path);
      }
      if (null != querys) {
      if (null != params) {
         StringBuilder sbQuery = new StringBuilder();
         for (Map.Entry<String, String> query : querys.entrySet()) {
         for (Map.Entry<String, String> query : params.entrySet()) {
            if (0 < sbQuery.length()) {
               sbQuery.append("&");
            }
@@ -243,7 +253,7 @@
               sbQuery.append(query.getKey());
               if (!StringUtils.isBlank(query.getValue())) {
                  sbQuery.append("=");
                  sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                  sbQuery.append(URLEncoder.encode(query.getValue(), StandardCharsets.UTF_8));
               }
            }
         }
@@ -256,40 +266,77 @@
   }
   private static HttpClient wrapClient(String host) {
      CloseableHttpClient httpClient = HttpClients.createDefault();
      if (host.startsWith("https://")) {
         sslClient(httpClient);
         return sslClient();
      }else{
         return HttpClients.createDefault();
      }
      return httpClient;
   }
//
//   private static void sslClient(HttpClient httpClient) {
//      try {
//         SSLContext ctx = SSLContext.getInstance("TLS");
//         X509TrustManager tm = new X509TrustManager() {
//            public X509Certificate[] getAcceptedIssuers() {
//               return null;
//            }
//
//            public void checkClientTrusted(X509Certificate[] xcs, String str) {
//
//            }
//
//            public void checkServerTrusted(X509Certificate[] xcs, String str) {
//
//            }
//         };
//         ctx.init(null, new TrustManager[] { tm }, null);
//         SSLSocketFactory ssf = new SSLSocketFactory(ctx);
//         ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
//         ClientConnectionManager ccm = httpClient.getConnectionManager();
//         SchemeRegistry registry = ccm.getSchemeRegistry();
//         registry.register(new Scheme("https", 443, ssf));
//      } catch (KeyManagementException ex) {
//         throw new RuntimeException(ex);
//      } catch (NoSuchAlgorithmException ex) {
//         throw new RuntimeException(ex);
//      }
//   }
   private static void sslClient(HttpClient httpClient) {
   /**
    * 在调用SSL之前需要重写验证方法,取消检测SSL
    * 创建ConnectionManager,添加Connection配置信息
    * @return HttpClient 支持https
    */
   private static HttpClient sslClient() {
      try {
         SSLContext ctx = SSLContext.getInstance("TLS");
         X509TrustManager tm = new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
         // 在调用SSL之前需要重写验证方法,取消检测SSL
         X509TrustManager trustManager = new X509TrustManager() {
            @Override public X509Certificate[] getAcceptedIssuers() {
               return null;
            }
            public void checkClientTrusted(X509Certificate[] xcs, String str) {
            }
            public void checkServerTrusted(X509Certificate[] xcs, String str) {
            }
            @Override public void checkClientTrusted(X509Certificate[] xcs, String str) {}
            @Override public void checkServerTrusted(X509Certificate[] xcs, String str) {}
         };
         ctx.init(null, new TrustManager[] { tm }, null);
         SSLSocketFactory ssf = new SSLSocketFactory(ctx);
         ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
         ClientConnectionManager ccm = httpClient.getConnectionManager();
         SchemeRegistry registry = ccm.getSchemeRegistry();
         registry.register(new Scheme("https", 443, ssf));
         SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
         ctx.init(null, new TrustManager[] { trustManager }, null);
         SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
         // 创建Registry
         RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
               .setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
               .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
         Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
               .register("http", PlainConnectionSocketFactory.INSTANCE)
               .register("https",socketFactory).build();
         // 创建ConnectionManager,添加Connection配置信息
         PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
         CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager)
               .setDefaultRequestConfig(requestConfig).build();
         return closeableHttpClient;
      } catch (KeyManagementException ex) {
         throw new RuntimeException(ex);
      } catch (NoSuchAlgorithmException ex) {
         throw new RuntimeException(ex);
      }
   }
}