import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Instant;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import com.google.gson.Gson;
public class Main {
static HttpClient client = HttpClient.newHttpClient();
public static void main(String[] args) throws NoSuchAlgorithmException, IOException, InterruptedException {
String key = "替换为校验签名";
String url = "Webhook地址";
long timestamp = Instant.now().getEpochSecond();
String sign = getSign(key, timestamp);
Map<String, Object> params = new HashMap<>();
params.put("应用参数1", "参数1的值");
params.put("应用参数2", "参数2的值");
RpaWebhookDto rpaWebhook = new RpaWebhookDto(Long.toString(timestamp), sign, params);
String requestBody = new Gson().toJson(rpaWebhook);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
System.out.println("调用成功");
return;
}
WebhookInvokeFailureDto res = new Gson().fromJson(response.body(), WebhookInvokeFailureDto.class);
System.out.println("调用失败");
System.out.println("失败原因:" + res.getDescription());
System.out.println("失败Code:" + res.getCode());
}
static String getSign(String secret, long timestamp) {
String stringToSign = timestamp + "\n" + secret;
try {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] result = mac.doFinal();
return Base64.getEncoder().encodeToString(result);
} catch (Exception e) {
throw new RuntimeException("getSign error", e);
}
}
static class RpaWebhookDto {
String Timestamp;
String Sign;
Map<String, Object> Params;
public RpaWebhookDto(String timestamp, String sign, Map<String, Object> params) {
Timestamp = timestamp;
Sign = sign;
Params = params;
}
}
static class WebhookInvokeFailureDto {
String Code;
String Description;
String RequestId;
}
}