From 72e72b8733cd2fd063f251bc7450c9e36b01f352 Mon Sep 17 00:00:00 2001 From: 童刚 <pBP8jclM@8yTJ@4h> Date: 星期三, 03 八月 2022 18:58:12 +0800 Subject: [PATCH] 111 --- src/main/java/com/hz/util/http/dto/HttpClientUtils.java | 319 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 319 insertions(+), 0 deletions(-) diff --git a/src/main/java/com/hz/util/http/dto/HttpClientUtils.java b/src/main/java/com/hz/util/http/dto/HttpClientUtils.java new file mode 100644 index 0000000..c24f3cd --- /dev/null +++ b/src/main/java/com/hz/util/http/dto/HttpClientUtils.java @@ -0,0 +1,319 @@ +package com.hz.util.http.dto; + +import org.apache.commons.lang.StringUtils; +import org.apache.http.HttpEntity; +import org.apache.http.NameValuePair; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.ssl.SSLContextBuilder; +import org.apache.http.ssl.TrustStrategy; +import org.apache.http.util.EntityUtils; + +import javax.net.ssl.SSLContext; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class HttpClientUtils { + + /** 鑾峰彇Http瀹㈡埛绔� */ + private static final CloseableHttpClient httpClient; + /** 璁剧疆榛樿缂栫爜 */ + public static final String CHARSET = "UTF-8"; + + /** 鍒濆鍖栬秴鏃舵椂闂撮厤缃�,骞堕厤缃敓鎴愰粯璁ttpClient瀵硅薄 */ + static { + RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build(); + httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); + } + + public static String doGet(String url, Map<String, String> params) { + return doGet(url, params, CHARSET); + } + + public static String doPost(String url, Map<String, String> params) { + return doPost(url, params, CHARSET); + } + + public static String doGetSSL(String url, Map<String, String> params) { + return doGetSSL(url, params, CHARSET); + } + + /** + * 鑾峰彇ip鍦板潃 + */ + public static String getIp(HttpServletRequest request) { + String ip = request.getHeader("x-forwarded-for"); + System.out.println("x-forwarded-for ip: " + ip); + if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) { + // 澶氭鍙嶅悜浠g悊鍚庝細鏈夊涓猧p鍊硷紝绗竴涓猧p鎵嶆槸鐪熷疄ip + if (ip.contains(",")) { + ip = ip.split(",")[0]; + } + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("HTTP_CLIENT_IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("HTTP_X_FORWARDED_FOR"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("X-Real-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + return ip; + } + + /** + * HTTP GET鑾峰彇鍐呭 + * + * @param url 璇锋眰鍦板潃 + * @param params 璇锋眰鍙傛暟 + * @param charset 缂栫爜(UTF-8) + * @return String + */ + public static String doGet(String url, Map<String, String> params, String charset) { + String result = null; + if (StringUtils.isBlank(url)) { + return null; + } + //鍝嶅簲妯″瀷 + CloseableHttpResponse response = null; + try { + //灏嗚姹傚弬鏁版嫾鎺rl鍦板潃鍚� + if (params != null && !params.isEmpty()) { + List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); + for (Map.Entry<String, String> entry : params.entrySet()) { + String value = entry.getValue(); + if (value != null) { + pairs.add(new BasicNameValuePair(entry.getKey(), value)); + } + } + url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset)); + } + //鍒涘缓http get璇锋眰 + HttpGet httpGet = new HttpGet(url); + //鐢卞鎴风鎵цget璇锋眰 + response = httpClient.execute(httpGet); + //鑾峰彇鍝嶅簲鐘舵�� + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != 200) { + httpGet.abort(); + throw new RuntimeException("HttpClient,error status code :" + statusCode); + } + //浠庡搷搴旀ā鍨嬩腑鑾峰彇鍝嶅簲瀹炰綋 + HttpEntity entity = response.getEntity(); + if (entity != null) { + result = EntityUtils.toString(entity, charset); + } + //鍏抽棴HttpEntity娴� + EntityUtils.consume(entity); + return result; + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + return result; + } + + public static String doPost(String url, String params, String charset) { + String result = null; + //鍝嶅簲妯″瀷 + CloseableHttpResponse response = null; + try { + //鍒涘缓http post璇锋眰 + HttpPost httpPost = new HttpPost(url); + if (params != null && !"".equals(params)) { + StringEntity stringEntity = new StringEntity(params); + stringEntity.setContentType("application/json"); + stringEntity.setContentEncoding(charset); + httpPost.setEntity(stringEntity); + //鐢卞鎴风鎵цpost璇锋眰 + response = httpClient.execute(httpPost); + HttpEntity entity = response.getEntity(); + if (entity != null) { + result = EntityUtils.toString(entity, charset); + } + //鍏抽棴HttpEntity娴� + EntityUtils.consume(entity); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + return result; + } + + /** + * HTTP POST鑾峰彇鍐呭 + * + * @param url 璇锋眰鍦板潃 + * @param params 璇锋眰鍙傛暟 + * @param charset 缂栫爜(UTF-8) + * @return String + */ + public static String doPost(String url, Map<String, String> params, String charset) { + String result = null; + if (StringUtils.isBlank(url)) { + return null; + } + //璇锋眰鍙傛暟 + List<NameValuePair> pairs = null; + //鍝嶅簲妯″瀷 + CloseableHttpResponse response = null; + try { + if (params != null && !params.isEmpty()) { + pairs = new ArrayList<NameValuePair>(params.size()); + for (Map.Entry<String, String> entry : params.entrySet()) { + String value = entry.getValue(); + if (value != null) { + pairs.add(new BasicNameValuePair(entry.getKey(), value)); + } + } + } + //鍒涘缓http post璇锋眰 + HttpPost httpPost = new HttpPost(url); + if (pairs != null && pairs.size() > 0) { + httpPost.setEntity(new UrlEncodedFormEntity(pairs, charset)); + } + //鐢卞鎴风鎵цpost璇锋眰 + response = httpClient.execute(httpPost); + //鑾峰彇鍝嶅簲鐘舵�� + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != 200) { + httpPost.abort(); + throw new RuntimeException("HttpClient,error status code :" + statusCode); + } + //浠庡搷搴旀ā鍨嬩腑鑾峰彇鍝嶅簲瀹炰綋 + HttpEntity entity = response.getEntity(); + if (entity != null) { + result = EntityUtils.toString(entity, charset); + } + //鍏抽棴HttpEntity娴� + EntityUtils.consume(entity); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + return result; + } + + /** + * HTTPS GET 鑾峰彇鍐呭 + * + * @param url 璇锋眰鐨剈rl鍦板潃 ?涔嬪墠鐨勫湴鍧� + * @param params 璇锋眰鐨勫弬鏁� + * @param charset 缂栫爜鏍煎紡 + * @return 椤甸潰鍐呭 + */ + public static String doGetSSL(String url, Map<String, String> params, String charset) { + if (StringUtils.isBlank(url)) { + return null; + } + String result = null; + CloseableHttpResponse response = null; + try { + if (params != null && !params.isEmpty()) { + List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); + for (Map.Entry<String, String> entry : params.entrySet()) { + String value = entry.getValue(); + if (value != null) { + pairs.add(new BasicNameValuePair(entry.getKey(), value)); + } + } + url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset)); + } + HttpGet httpGet = new HttpGet(url); + // https 娉ㄦ剰杩欓噷鑾峰彇https鍐呭锛屼娇鐢ㄤ簡蹇界暐璇佷功鐨勬柟寮忥紝褰撶劧杩樻湁鍏朵粬鐨勬柟寮忔潵鑾峰彇https鍐呭 + CloseableHttpClient httpsClient = HttpClientUtils.createSSLClientDefault(); + response = httpsClient.execute(httpGet); + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != 200) { + httpGet.abort(); + throw new RuntimeException("HttpClient,error status code :" + statusCode); + } + HttpEntity entity = response.getEntity(); + if (entity != null) { + result = EntityUtils.toString(entity, charset); + } + EntityUtils.consume(entity); + return result; + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + return result; + } + + /** + * 杩欓噷鍒涘缓浜嗗拷鐣ユ暣鏁伴獙璇佺殑CloseableHttpClient瀵硅薄 + */ + public static CloseableHttpClient createSSLClientDefault() { + try { + SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { + // 淇′换鎵�鏈� + public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { + return true; + } + }).build(); + SSLConnectionSocketFactory ssl = new SSLConnectionSocketFactory(sslContext); + return HttpClients.custom().setSSLSocketFactory(ssl).build(); + } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { + e.printStackTrace(); + } + return HttpClients.createDefault(); + } + +} -- Gitblit v1.8.0