public class DingTalkSignature {
private static final String SECRET = "加签密钥";
private static final String WEBHOOK_URL = "Webhook";
private static final OkHttpClient CLIENT = new OkHttpClient();
public static void sendMessage(String message) {
try {
// 生成签名
String timestamp = String.valueOf(Instant.now().toEpochMilli());
String stringToSign = timestamp + "\n" + SECRET;
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] signBytes = sha256_HMAC.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
String sign = Base64.getEncoder().encodeToString(signBytes);
Charset charset = StandardCharsets.UTF_8;
String charsetName = charset.name();
// 构造请求URL
String url = WEBHOOK_URL + "×tamp=" + timestamp + "&sign=" + URLEncoder.encode(sign, charsetName);
// 构造请求体
String jsonPayload = "{\"msgtype\": \"text\", \"text\": {\"content\": \"" + message + "\"}, \"at\": {\"atMobiles\": [], \"isAtAll\": true}}";
// String jsonPayload = "{\"msgtype\": \"text\", \"text\": {\"content\": \"" + message + "\"}}";
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonPayload);
// 发送请求
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Content-Type", "application/json")
.build();
try (Response response = CLIENT.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
} catch (IOException e) {
System.err.println("Error sending message: " + e.getMessage());
}
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
System.err.println("Algorithm or key exception occurred: " + e.getMessage());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
sendMessage("测试消息");
}
}
Java发送钉钉消息(加签)
于 2024-03-08 08:53:19 首次发布