package project.web.api;
|
|
import cn.hutool.core.util.RandomUtil;
|
import cn.hutool.crypto.SecureUtil;
|
import cn.hutool.json.JSONUtil;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
|
import java.io.BufferedReader;
|
import java.io.IOException;
|
import java.io.InputStreamReader;
|
import java.io.OutputStream;
|
import java.net.HttpURLConnection;
|
import java.net.URL;
|
import java.util.HashMap;
|
import java.util.Map;
|
|
|
public class UdunUtils {
|
private static Logger logger = LoggerFactory.getLogger(UdunUtils.class);
|
|
public static String post(String gateway, String merchantKey, String path, String body) {
|
try {
|
// 创建 URL 对象
|
URL url = new URL(gateway+path);
|
|
// 打开连接
|
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
|
// 设置请求方法为 POST
|
connection.setRequestMethod("POST");
|
|
// 设置请求头
|
connection.setRequestProperty("Content-Type", "application/json");
|
connection.setRequestProperty("Accept", "application/json");
|
|
// 启用输入输出流
|
connection.setDoOutput(true);
|
|
String rawBody = parseParams(merchantKey, body);
|
|
// 写入请求体
|
try (OutputStream os = connection.getOutputStream()) {
|
byte[] input = rawBody.getBytes("utf-8");
|
os.write(input, 0, input.length);
|
}
|
|
// 获取响应代码
|
int responseCode = connection.getResponseCode();
|
|
// 读取响应
|
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
|
String inputLine;
|
StringBuilder response = new StringBuilder();
|
while ((inputLine = in.readLine()) != null) {
|
response.append(inputLine);
|
}
|
return response.toString();
|
}
|
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
return null;
|
}
|
|
public static String parseParams(String merchantKey, String body) {
|
Map<String, String> params = new HashMap<>();
|
String timestamp = System.currentTimeMillis() + "";
|
String nonce = RandomUtil.randomString(6);
|
String sign = sign(merchantKey, timestamp, nonce, body);
|
params.put("timestamp", timestamp);
|
params.put("nonce", nonce);
|
params.put("sign", sign);
|
params.put("body", body);
|
return JSONUtil.toJsonStr(params);
|
}
|
|
public static String sign(String key, String timestamp, String nonce, String body) {
|
String raw = body + key + nonce + timestamp;
|
return SecureUtil.md5(raw);
|
}
|
|
public static boolean checkSign(String key, String timestamp, String nonce, String body, String sign) {
|
String checkSign = sign(key, timestamp, nonce, body);
|
return checkSign.equals(sign);
|
}
|
}
|