Java对接钉钉机器人发送消息API

依赖的Http工具地址

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class DingDingUtil {
    private static final String SECRET = "";
    private static final String ACCESS_TOKEN = "";
    /**
     * 发送钉钉通知
     *
     * @param msg 钉钉通知信息
     */
    public static void sendMsg(String msg) {
        try {
            long timestamp = System.currentTimeMillis();
            String url = new StringBuilder("https://oapi.dingtalk.com/robot/send")
                    .append("?access_token=").append(ACCESS_TOKEN)
                    .append("×tamp=").append(timestamp)
                    .append("&sign=").append(getSign(SECRET, timestamp))
                    .toString();
            Map actionCard = new HashMap<>();
            actionCard.put("text", msg);
            Map param = new HashMap<>();
            param.put("actionCard", actionCard);
            param.put("msgtype", "actionCard");
            ResponseResult responseResult = HttpClientUtil.doHttpPostJson(url, JSONObject.toJSONString(param));
            log.info("钉钉发送消息【{}】返回结果:{}", msg, responseResult);
        } catch (Exception e) {
            log.error("钉钉发送消息【{}】异常 异常堆栈信息", msg, e);
        }
    }
    private static String getSign(String tcSecret, long timestamp) throws Exception {
        String stringToSign = timestamp + "\n" + tcSecret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(tcSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        return URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
    }
    
}

你可能感兴趣的:(Java,java)