Java发送钉钉消息(加签)

本文详细介绍了如何在Java中使用DingTalkAPI发送带有签名的消息,包括生成签名、构造请求URL和构建请求体的过程。
摘要由CSDN通过智能技术生成
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 + "&timestamp=" + 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发送钉钉消息,可以通过使用钉钉开放平台提供的API来实现。具体步骤如下: 1. 首先,你需要在钉钉开放平台上创建一个机器人,获得机器人的Webhook URL。Webhook URL是用于接收和发送钉钉消息的地址。 2. 在Java项目中使用HttpClient或者其他相关的HTTP库发送HTTP POST请求,将消息以JSON格式发送钉钉机器人的Webhook URL。向Webhook URL发送消息一般包括以下信息: - "msgtype"字段,表示消息类型为图文消息。 - "link"字段,包括图文消息的标题、消息内容、消息封面图片等信息。 下面是一个使用HttpClient发送钉钉图文消息的示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.io.IOException; public class DingTalkMessageSender { private static final String WEBHOOK_URL = "your_webhook_url"; public static void sendNewsMessage() throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(WEBHOOK_URL); // 构建图文消息的JSON字符串 String messageJSON = "{\"msgtype\":\"link\",\"link\":{\"title\":\"图文消息标题\",\"text\":\"图文消息内容\",\"picUrl\":\"图片地址\",\"messageUrl\":\"消息点击跳转链接\"}}"; // 设置请求header httpPost.addHeader("Content-Type", "application/json; charset=utf-8"); // 设置请求内容 HttpEntity httpEntity = new StringEntity(messageJSON, ContentType.APPLICATION_JSON); httpPost.setEntity(httpEntity); // 发送请求 httpClient.execute(httpPost); } public static void main(String[] args) { try { sendNewsMessage(); } catch (IOException e) { e.printStackTrace(); } } } ``` 上述代码中,你需要将`your_webhook_url`替换成你钉钉机器人的Webhook URL,然后调用`sendNewsMessage`方法即可发送图文消息。 这样,你就可以在Java中使用钉钉的API发送图文消息了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值