This commit is contained in:
lu7213 committed 2025-12-02 23:07:47 +08:00
1 parent 81eca8933a
commit 345f906c35
540 files changed
+494222 -90

No files matched your search

@@ -0,0 +1,578 @@
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;
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 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 httpClient = null;
if (url.startsWith("https")) {
httpClient = getHttpsClient();
} else {
httpClient = getHttpClient();
}
CloseableHttpResponse response = this.send(httpClient, 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 httpClient = null;
if (url.startsWith("https")) {
httpClient = getHttpsClient();
} else {
httpClient = getHttpClient();
}
CloseableHttpResponse response = this.send(httpClient, 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 httpClient = null;
if (url.startsWith("https")) {
httpClient = getHttpsClient();
} else {
httpClient = getHttpClient();
}
CloseableHttpResponse response = this.send(httpClient, 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 httpClient = null;
if (url.startsWith("https")) {
httpClient = getHttpsClient();
} else {
httpClient = getHttpClient();
}
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) httpClient.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);
}
}
@@ -0,0 +1,28 @@
package com.luqj.util;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class HttpsTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}
@@ -0,0 +1,129 @@
package com.luqj.util;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RequestHelper {
private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream";
public static Map<String, String> fileToContentTypeMap = new HashMap<String, String>();
static {
fileToContentTypeMap.put(".atom", "application/atom+xml");
fileToContentTypeMap.put(".rss", "application/rss+xml");
fileToContentTypeMap.put(".xml", "application/xml");
fileToContentTypeMap.put(".csv", "text/csv");
fileToContentTypeMap.put(".txt", "text/plain");
}
public static String getContentTypeForFile(File file) {
String contentType = fileToContentTypeMap.get(getFileExtension(file));
if (contentType != null) return contentType;
try {
contentType = Files.probeContentType(file.toPath());
} catch (IOException ignored) {
}
return contentType != null ? contentType : DEFAULT_CONTENT_TYPE;
}
private static String getFileExtension(File file) {
String fileName = file.getName();
int index = fileName.lastIndexOf('.');
if (index == -1) return "";
return fileName.substring(index, fileName.length());
}
private static 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();
}
}
public static int getContentLength(Map<String, Object> allParams, String boundary) throws IOException {
int contentLength = 0;
for (Map.Entry entry : allParams.entrySet()) {
contentLength += ("--" + boundary + "\r\n").length();
if (entry.getValue() instanceof File) {
File file = (File) entry.getValue();
String contentType = getContentTypeForFile(file);
contentLength += getLengthAndLog( "Content-Disposition: form-data; name=\"" + entry.getKey() + "\"; filename=\"" + file.getName() + "\"\r\n");
if (contentType != null) {
contentLength += getLengthAndLog( "Content-Type: " + contentType + "\r\n");
}
contentLength += getLengthAndLog( "\r\n");
contentLength += file.length();
contentLength += getLengthAndLog( "\r\n");
} else if (entry.getValue() instanceof byte[]) {
byte[] bytes = (byte[]) entry.getValue();
contentLength += getLengthAndLog( "Content-Disposition: form-data; name=\"" + entry.getKey() + "\"; filename=\"" + "chunkfile" + "\"\r\n");
contentLength += bytes.length;
contentLength += getLengthAndLog( "\r\n");
} else {
contentLength += getLengthAndLog( "Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
contentLength += getLengthAndLog( convertToString(entry.getValue()));
contentLength += getLengthAndLog( "\r\n");
}
}
contentLength += getLengthAndLog( "--" + boundary + "--\r\n");
return contentLength;
}
private static int getLengthAndLog(String input) throws IOException {
return input.getBytes("UTF-8").length;
}
public static String constructUrlString(String apiUrl, Map<String, Object> allParams) throws IOException {
StringBuilder urlString = new StringBuilder(apiUrl);
boolean firstEntry = true;
for (Map.Entry entry : allParams.entrySet()) {
urlString.append((firstEntry ? "?" : "&") + URLEncoder.encode(entry.getKey().toString(), "UTF-8") + "=" + URLEncoder.encode(convertToString(entry.getValue()), "UTF-8"));
firstEntry = false;
}
return urlString.toString();
}
public static ListenableFuture<ResponseWrapper> invoke(okhttp3.OkHttpClient client, okhttp3.Request request) {
final SettableFuture<ResponseWrapper> future = SettableFuture.create();
client.newCall(request).enqueue(
new okhttp3.Callback() {
@Override
public void onFailure(final okhttp3.Call call, IOException e) {
future.setException(
new Exception(e)
);
}
@Override
public void onResponse(okhttp3.Call call, final okhttp3.Response response) throws IOException {
future.set(new ResponseWrapper(response.body().string(), convertToString(response.headers())));
}
});
return future;
}
}
@@ -0,0 +1,19 @@
package com.luqj.util;
public class ResponseWrapper {
private String body;
private String header;
public ResponseWrapper(String body, String header) {
this.body = body;
this.header = header;
}
public String getBody() {
return this.body;
}
public String getHeader() {
return this.header;
}
}
@@ -0,0 +1,92 @@
package com.luqj.util;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
public class SignatureUtil {
/**
* 生成签名
* @param params 业务参数(不包含signature)
* @param apiToken API认证密钥(例如 epusdt_password_xasddawqe)
* @return 生成的MD5签名(32位小写)
*/
public static String generateSignature(Map<String, Object> params, String apiToken) {
// 1. 按 ASCII 排序
SortedMap<String, Object> sortedParams = new TreeMap<>(params);
// 2. 拼接成 key=value&key=value
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, Object> entry : sortedParams.entrySet()) {
// if(entry.getValue() instanceof Double){
// Double val = (Double) entry.getValue();
// BigDecimal amount = new BigDecimal(val);
// if (entry.getValue() != null) {
// sb.append(entry.getKey()).append("=").append( amount.setScale(2, RoundingMode.DOWN).toPlainString()).append("&");
// }
// }else if(entry.getValue() instanceof BigDecimal){
// BigDecimal amount = (BigDecimal) entry.getValue();
// if (entry.getValue() != null) {
// sb.append(entry.getKey()).append("=").append( amount.setScale(2, RoundingMode.DOWN).toPlainString()).append("&");
// }
// }else {
// if (entry.getValue() != null && !entry.getValue().toString().isEmpty()) {
// sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
// }
// }
if (entry.getValue() != null && !entry.getValue().toString().isEmpty()) {
sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
}
// 去掉最后一个 & 符号
sb.setLength(sb.length() - 1);
// 3. 拼接密钥
sb.append(apiToken); // 注意:不是加 &,是直接拼接密钥!!!
// 4. MD5加密
return md5(sb.toString()).toLowerCase();
}
// MD5算法实现
private static String md5(String text) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(text.getBytes("UTF-8"));
StringBuilder hexString = new StringBuilder();
for (byte b : digest) {
hexString.append(String.format("%02x", b & 0xff));
}
return hexString.toString();
} catch (Exception e) {
throw new RuntimeException("MD5 error: " + e.getMessage(), e);
}
}
// 测试方法
public static void main(String[] args) throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("order_id", System.currentTimeMillis()+"");
params.put("app_id", "1");
params.put("amount", "64.01");
params.put("notify_url", "http://127.0.0.1:5005/transfer/trc/notify");
params.put("redirect_url", "http://example.com/redirect"); //pay/checkout-counter/xxx 支付成功后得回调地址
String token = "lqj";
String signature = generateSignature(params, token);
//c50576484554b282f6c2b53097217464
System.out.println("Signature = " + signature);
HttpHelper httpHelper = new HttpHelper();
HashMap<String, Object> headers = new HashMap<>();
// headers.put("Content-Type", "application/json");
params.put("signature", signature);
String result =httpHelper.playLoad("post","https://yougc.com/usdt/api/v1/order/create-transaction"
,headers,params,"application/json","utf-8");
System.out.println(result);
}
}