From 20d5ea0db2e8121600e5c8459d642d9180510940 Mon Sep 17 00:00:00 2001 From: liurunyu <lry9898@163.com> Date: 星期一, 08 一月 2024 13:10:36 +0800 Subject: [PATCH] 优化代码,把过期的代码替换掉,主要针对apache的https的请求 --- pipIrr-platform/pipIrr-common/src/main/java/com/dy/common/util/HttpUtils.java | 245 +++++++++++++++++++++++++++++------------------- 1 files changed, 146 insertions(+), 99 deletions(-) diff --git a/pipIrr-platform/pipIrr-common/src/main/java/com/dy/common/util/HttpUtils.java b/pipIrr-platform/pipIrr-common/src/main/java/com/dy/common/util/HttpUtils.java index 633f940..05cee30 100644 --- a/pipIrr-platform/pipIrr-common/src/main/java/com/dy/common/util/HttpUtils.java +++ b/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 鏈嶅姟绔疷RI + * @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 鏈嶅姟绔疷RI + * @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 鏈嶅姟绔疷RI + * @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 鏈嶅姟绔疷RI + * @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 鏈嶅姟绔疷RI + * @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 鏈嶅姟绔疷RI + * @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 鏈嶅姟绔疷RI + * @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) { + /** + * 鍦ㄨ皟鐢⊿SL涔嬪墠闇�瑕侀噸鍐欓獙璇佹柟娉曪紝鍙栨秷妫�娴婼SL + * 鍒涘缓ConnectionManager锛屾坊鍔燙onnection閰嶇疆淇℃伅 + * @return HttpClient 鏀寔https + */ + private static HttpClient sslClient() { try { - SSLContext ctx = SSLContext.getInstance("TLS"); - X509TrustManager tm = new X509TrustManager() { - public X509Certificate[] getAcceptedIssuers() { + // 鍦ㄨ皟鐢⊿SL涔嬪墠闇�瑕侀噸鍐欓獙璇佹柟娉曪紝鍙栨秷妫�娴婼SL + 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锛屾坊鍔燙onnection閰嶇疆淇℃伅 + 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); } } + } -- Gitblit v1.8.0