Files
usdt/luqj-common/src/main/java/com/luqj/util/HttpHelper.java
T
2026-08-13 02:47:05 -04:00

624 lines
24 KiB
Java

package com.luqj.util;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
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.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
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.util.EntityUtils;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.*;
import java.security.cert.CertificateException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.GZIPInputStream;
@Slf4j
public class HttpHelper {
private String proxyHost;
private Integer proxyPort;
private CloseableHttpClient httpsClient = null;
private CloseableHttpClient httpClient = null;
public String getProxyHost() {
return proxyHost;
}
public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
}
public Integer getProxyPort() {
return proxyPort;
}
public void setProxyPort(Integer proxyPort) {
this.proxyPort = proxyPort;
}
public synchronized void closeClient(){
try {
if (httpsClient != null) {
httpsClient.close();
httpsClient = null;
}
if (httpClient != null) {
httpClient.close();
httpClient = null;
}
}catch (Exception e){
log.error(e.getMessage(),e);
}
if (cm != null) {
cm.close();
}
cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(500);
cm.setDefaultMaxPerRoute(5);
}
public static void main(String[] args) throws Exception {
BigDecimal decimal = new BigDecimal("1").divide(new BigDecimal(100));
esListense();
}
/**
* 读取网络文本
*
* @param sourcePath
* @return
*/
public List<String> readHttpFile(String sourcePath) {
String line;
int lineNum = 0;
List<String> list = new ArrayList<>();
BufferedReader reader = null;
try {
URL url = new URL(sourcePath);
reader = new BufferedReader(new InputStreamReader(url.openStream(), "gbk"));
while ((line = reader.readLine()) != null) {
lineNum++;
list.add(line);
}
} catch (Exception ie) {
ie.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
public List<String> readGzFile(String url) throws IOException {
InputStream in = new GZIPInputStream(new FileInputStream(url));
List<String> list = IOUtils.readLines(in, "UTF-8");
return list;
}
public List<String> readHttpGzFile(String sourcePath) {
List<String> list = new ArrayList<>();
BufferedReader reader = null;
try {
URL url = new URL(sourcePath);
InputStream in = new GZIPInputStream(url.openStream());
list = IOUtils.readLines(in, "UTF-8");
} catch (Exception ie) {
ie.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
public CloseableHttpClient getHttpsClient() throws Exception {
SSLContext sslcontext = SSLContexts.custom().useSSL().build();
sslcontext.init(null, new X509TrustManager[]{new HttpsTrustManager()}, new SecureRandom());
SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(500000)
.setStaleConnectionCheckEnabled(true)
.build();
RequestConfig requestConfig = null;
if (StringUtils.isNotBlank(proxyHost) && null != proxyPort) {
// setProxy(new HttpHost("lu7213.6655.la", 57301))
// setProxy(new HttpHost("127.0.0.1", 19180))
requestConfig = RequestConfig.copy(defaultRequestConfig).setProxy(new HttpHost(proxyHost, proxyPort))
.build();
} else {
requestConfig = RequestConfig.copy(defaultRequestConfig).build();
}
CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(factory).setDefaultRequestConfig(requestConfig).build();
return client;
}
/**
* 导入证书
*
* @return
* @throws KeyStoreException
* @throws NoSuchAlgorithmException
* @throws CertificateException
* @throws IOException
* @throws KeyManagementException
*/
private SSLContext getSSLContext() throws KeyStoreException,
NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File("my.keystore"));
try {
trustStore.load(instream, "nopassword".toCharArray());
} finally {
instream.close();
}
return SSLContexts.custom()
.loadTrustMaterial(trustStore)
.build();
}
// es 7.4 白嫖命令
private static boolean esListense() throws Exception {
HttpHelper httpHelper = new HttpHelper();
HashMap<String, Object> headers = new HashMap<>();
// headers.put("Content-Type", "application/json");
HashMap<String, Object> map = new HashMap<>();
map.put("access_token", "1278491352545154|4fa79654c00caab794a70afee2d769c2");
map.put("input_token", "EAASKxZCbqt4IBAOwxuyFEZCynraaVQtOrMnwkj301sxydRYZBiZBUe1REIV1zcrXvSC6nsnPVMG1YpB645OsRACOjQ9C9T4lFJxQI1rPon2p2Ww8onXsKytaOcqaKFf2f4EZAA4doPxGcJoBiCnKh0g7EdhjZBQrfpC1Q05N87fLUlKHE3ZAQddLeZAIKBaXcoyDVhqTSWVGoKlghLQvMpnJNeXmRyQTSIAZD");
// ResponseWrapper result = httpHelper.sendGet("https://graph.facebook.com/debug_token", map);
// httpHelper.setProxyHost("192.168.2.4");
// httpHelper.setProxyPort(29180);
// String result = httpHelper.getlHttpResult("https://graph.facebook.com/debug_token", "GET", headers, map);
// System.out.println(result);
// HashMap headers = new HashMap<>();
//// headers.put("Content-Type", "application/json");
String data = "{\"license\":{\"uid\":\"64311a78-1da8-4242-801d-1919b2ee6373\",\"type\":\"platinum\",\"issue_date_in_millis\":1591660800000,\"expiry_date_in_millis\":2516630400000,\"max_nodes\":100,\"issued_to\":\"qungjie lu (dragon)\",\"issuer\":\"Web Form\",\"signature\":\"AAAAAwAAAA3TbuzQUBHKydhRaMl8AAABmC9ZN0hjZDBGYnVyRXpCOW5Bb3FjZDAxOWpSbTVoMVZwUzRxVk1PSmkxaktJRVl5MUYvUWh3bHZVUTllbXNPbzBUemtnbWpBbmlWRmRZb25KNFlBR2x0TXc2K2p1Y1VtMG1UQU9TRGZVSGRwaEJGUjE3bXd3LzRqZ05iLzRteWFNekdxRGpIYlFwYkJiNUs0U1hTVlJKNVlXekMrSlVUdFIvV0FNeWdOYnlESDc3MWhlY3hSQmdKSjJ2ZTcvYlBFOHhPQlV3ZHdDQ0tHcG5uOElCaDJ4K1hob29xSG85N0kvTWV3THhlQk9NL01VMFRjNDZpZEVXeUtUMXIyMlIveFpJUkk2WUdveEZaME9XWitGUi9WNTZVQW1FMG1DenhZU0ZmeXlZakVEMjZFT2NvOWxpZGlqVmlHNC8rWVVUYzMwRGVySHpIdURzKzFiRDl4TmM1TUp2VTBOUlJZUlAyV0ZVL2kvVk10L0NsbXNFYVZwT3NSU082dFNNa2prQ0ZsclZ4NTltbU1CVE5lR09Bck93V2J1Y3c9PQAAAQBCUpzI7WOa8sBex3uA0Ag2ELeK9+bTX/GPpqKFEoEU6tdWyxxXsfwC1a8+FTkDmm/96jAm7x86wlgu3vimq7nK2ddMjNub3zZd4TAa3pRZfyNnJrlWzDIzyKwHI1N13YB4cEnrSgf+Hj/czIcLcFjTr7IEgXIuc1kfeEmghGLWVKZkHaoeTStWt5+3w/xwzs0ieacWp+FFkJv06ywEf96HusMSc1ExrRL/4JRY+zJiMjupxvrNSm3VP6K2I1RhR+XLXM/9d71jxPXFtFbY1IyAjHOviie7baszbR+eD3F1uHFOoR7WpKNYkXxVF+002HYtoKI4OEN2t6PXx12yAlXM\",\"start_date_in_millis\":1591660800000}}";
String result = httpHelper.playLoad("put", "http://192.168.2.176:9200/_xpack/license", headers, data, "application/json", "utf-8");
System.out.println(result);
return true;
}
private PoolingHttpClientConnectionManager cm;
public HttpHelper() {
cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(500); // 整个连接池最大连接数
cm.setDefaultMaxPerRoute(5); // 每路由最大连接数,默认值是2
}
/**
* 通过连接池获取HttpClient
*
* @return
*/
private CloseableHttpClient getHttpClient() {
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000000)
.setStaleConnectionCheckEnabled(true)
.build();
RequestConfig requestConfig = null;
if (StringUtils.isNotBlank(proxyHost) && null != proxyPort) {
// setProxy(new HttpHost("lu7213.6655.la", 57301))
// setProxy(new HttpHost("127.0.0.1", 19180))
requestConfig = RequestConfig.copy(defaultRequestConfig).setProxy(new HttpHost(proxyHost, proxyPort))
.build();
} else {
requestConfig = RequestConfig.copy(defaultRequestConfig).build();
}
return HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig).build();
}
private ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> param : params.entrySet()) {
pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
}
return pairs;
}
/**
* 发送http
*
* @param url
* @param method
* @param headers
* @return
* @throws Exception
*/
public CloseableHttpResponse send(CloseableHttpClient httpClient, String url, String method, Map<String, Object> headers) throws Exception {
URIBuilder ub = new URIBuilder();
ub.setPath(url);
HttpRequestBase http = null;
if (method.toLowerCase().equals("put")) {
http = new HttpPut(ub.build());
}
if (method.toLowerCase().equals("post")) {
http = new HttpPost(ub.build());
}
if (method.toLowerCase().equals("get")) {
http = new HttpGet(ub.build());
}
if (method.toLowerCase().equals("delete")) {
http = new HttpDelete(ub.build());
}
for (Map.Entry<String, Object> param : headers.entrySet()) {
http.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
try {
return httpClient.execute(http);
} catch (Exception e) {
throw e;
}
}
public CloseableHttpResponse send(CloseableHttpClient httpClient, String url, String method) throws Exception {
URIBuilder ub = new URIBuilder();
ub.setPath(url);
HttpRequestBase http = null;
if (method.toLowerCase().equals("put")) {
http = new HttpPut(ub.build());
}
if (method.toLowerCase().equals("post")) {
http = new HttpPost(ub.build());
}
if (method.toLowerCase().equals("get")) {
http = new HttpGet(ub.build());
}
if (method.toLowerCase().equals("delete")) {
http = new HttpDelete(ub.build());
}
try {
return httpClient.execute(http);
} catch (Exception e) {
throw e;
}
}
/**
* 发送http
*
* @param url
* @param method
* @param headers
* @param params
* @return
* @throws Exception
*/
public CloseableHttpResponse send(CloseableHttpClient httpClient, String url, String method, Map<String, Object> headers, Map<String, Object> params) throws Exception {
URIBuilder ub = new URIBuilder();
ub.setPath(url);
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
if (method.toLowerCase().equals("put")) {
ub.setParameters(pairs);
HttpPut http = null;
if (pairs.size() > 0) {
http = new HttpPut(ub.build());
} else {
http = new HttpPut(url);
}
for (Map.Entry<String, Object> param : headers.entrySet()) {
http.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
return httpClient.execute(http);
}
if (method.toLowerCase().equals("post")) {
ub.setParameters(pairs);
HttpPost http = null;
if (pairs.size() > 0) {
http = new HttpPost(ub.build());
} else {
http = new HttpPost(url);
}
for (Map.Entry<String, Object> param : headers.entrySet()) {
http.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
http.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
return httpClient.execute(http);
}
if (method.toLowerCase().equals("get")) {
HttpGet http = null;
if (pairs.size() > 0) {
ub.setParameters(pairs);
String path = ub.toString();
if(path.startsWith("/")) {
http = new HttpGet(path.substring(1));
}else{
http = new HttpGet(ub.build());
}
} else {
http = new HttpGet(url);
}
for (Map.Entry<String, Object> param : headers.entrySet()) {
http.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
// HttpHost target = new HttpHost(InetAddress.,ub.getHost(),ub.getPort(),ub.getScheme());
return httpClient.execute(http);
}
if (method.toLowerCase().equals("delete")) {
ub.setParameters(pairs);
HttpDelete http = null;
if (pairs.size() > 0) {
http = new HttpDelete(ub.build());
} else {
http = new HttpDelete(url);
}
for (Map.Entry<String, Object> param : headers.entrySet()) {
http.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
return httpClient.execute(http);
}
if (method.toLowerCase().equals("options")) {
ub.setParameters(pairs);
HttpOptions http = null;
if (pairs.size() > 0) {
http = new HttpOptions(ub.build());
} else {
http = new HttpOptions(url);
}
for (Map.Entry<String, Object> param : headers.entrySet()) {
http.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
return httpClient.execute(http);
}
return null;
}
public ResponseWrapper sendGet(String apiUrl, Map<String, Object> allParams) throws Exception {
URL url = new URL(RequestHelper.constructUrlString(apiUrl, allParams));
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "fbbizsdk-java-v3.3");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
return readResponse(con);
}
private ResponseWrapper readResponse(HttpsURLConnection con) throws Exception {
try {
int responseCode = con.getResponseCode();
String header = convertToString(con.getHeaderFields());
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return new ResponseWrapper(response.toString(), header);
} catch (Exception e) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
throw new Exception(response.toString(), e);
}
}
private String convertToString(Object input) {
if (input == null) {
return "null";
} else if (input instanceof Map) {
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.STATIC)
.excludeFieldsWithModifiers(Modifier.PROTECTED)
.disableHtmlEscaping()
.create();
return gson.toJson((Map) input);
} else if (input instanceof List) {
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.STATIC)
.excludeFieldsWithModifiers(Modifier.PROTECTED)
.disableHtmlEscaping()
.create();
return gson.toJson((List) input);
} else {
return input.toString();
}
}
/**
* 处理Http请求
*
* @return
*/
public String getlHttpResult(String url, String method, Map<String, Object> headers, Map<String, Object> params) throws Exception {
CloseableHttpClient tempClient = null;
if (url.startsWith("https")) {
if(httpsClient == null){
httpsClient = getHttpsClient();
}
tempClient = httpsClient;
} else {
if(httpClient == null) {
httpClient = getHttpClient();
}
tempClient = httpClient;
}
CloseableHttpResponse response = this.send(tempClient, url, method, headers, params);
if (method.toLowerCase().equals("options")) {
return response.getStatusLine().getStatusCode() + "";
} else {
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, Charset.forName("UTF-8"));
// httpClient.close();
response.close();
return result;
}
return "";
}
}
public String getlHttpResultCode(String url, String method, Map<String, Object> headers, Map<String, Object> params) throws Exception {
CloseableHttpClient tempClient = null;
if (url.startsWith("https")) {
if(httpsClient == null){
httpsClient = getHttpsClient();
}
tempClient = httpsClient;
} else {
if(httpClient == null) {
httpClient = getHttpClient();
}
tempClient = httpClient;
}
CloseableHttpResponse response = this.send(tempClient, url, method, headers, params);
return response.getStatusLine().getStatusCode() + "";
}
public Boolean testHttp(String url, String method, Map<String, Object> headers, Map<String, Object> params) throws Exception {
CloseableHttpClient tempClient = null;
if (url.startsWith("https")) {
if(httpsClient == null){
httpsClient = getHttpsClient();
}
tempClient = httpsClient;
} else {
if(httpClient == null) {
httpClient = getHttpClient();
}
tempClient = httpClient;
}
CloseableHttpResponse response = this.send(tempClient, url, method, headers, params);
boolean result = response.getStatusLine().getStatusCode() == 200;
response.close();
return result;
}
public void clear() {
cm.close();
}
public String playLoad(String method, String url, Map<String, Object> headersMap, Object data, String contentType, String charset) throws Exception {
CloseableHttpClient tempClient = null;
if (url.startsWith("https")) {
if(httpsClient == null){
httpsClient = getHttpsClient();
}
tempClient = httpsClient;
} else {
if(httpClient == null) {
httpClient = getHttpClient();
}
tempClient = httpClient;
}
String result = null;
HttpEntityEnclosingRequestBase httpEntityEnclosingRequestBase = null;
if ("post".equalsIgnoreCase(method)) {
httpEntityEnclosingRequestBase = new HttpPost(url);
} else if ("put".equalsIgnoreCase(method)) {
httpEntityEnclosingRequestBase = new HttpPut(url);
} else if ("get".equalsIgnoreCase(method)) {
httpEntityEnclosingRequestBase = new HttpEntityEnclosingRequestBase() {
@Override
public String getMethod() {
return "GET";
}
};
httpEntityEnclosingRequestBase.setURI(new URI(url));
}
for (Map.Entry<String, Object> param : headersMap.entrySet()) {
httpEntityEnclosingRequestBase.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
httpEntityEnclosingRequestBase.addHeader("Content-Type", contentType);
String json = "";
if (data instanceof String) {
json = String.valueOf(data);
} else {
json = JSONObject.toJSONString(data);
}
StringEntity entity = new StringEntity(json, charset);
// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
httpEntityEnclosingRequestBase.setEntity(entity);
// 响应模型
CloseableHttpResponse response = null;
try {
// 由客户端执行(发送)Post请求
response = (CloseableHttpResponse) tempClient.execute(httpEntityEnclosingRequestBase);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity);
}
} catch (Exception e) {
log.error(e.getMessage());
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
log.error(e.getMessage());
}
}
return result;
}
/**
* 替换指定格式的日期
*
* @param value
* @return
*/
public String replaceCurDate(String value) {
String cur = formatDate(new Date(), "yyyyMMddHHmm");
String result = value.replaceAll("\\$\\{yyyyMMddHHmm\\}", cur);
cur = formatDate(new Date(), "yyyyMMddHH");
result = result.replaceAll("\\$\\{yyyyMMddHH\\}", cur);
cur = formatDate(new Date(), "yyyyMMdd");
result = result.replaceAll("\\$\\{yyyyMMdd\\}", cur);
cur = formatDate(new Date(), "yyyyMM");
result = result.replaceAll("\\$\\{yyyyMM\\}", cur);
return result;
}
public String formatDate(final Date date, final String pattern) {
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
return formatter.format(date);
}
}