1.获取到机器人的webhook以及密钥

2.在springboot中添加相应的依赖
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version> <!-- 请根据需要使用最新的版本 -->
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>alibaba-dingtalk-service-sdk</artifactId>
<version>1.0.1</version>
</dependency>
3.编写钉钉客户端工具类(这里要写你的机器人的webhook 和 密钥)
@Component
public class DingDing {
public void sendMessage(String message) throws ApiException {
String getKey = getKey();
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?access_token=webhook" + getKey + "");
OapiRobotSendRequest request = new OapiRobotSendRequest();
//发送消息的类型
request.setMsgtype("text");
OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
text.setContent(message);
request.setText(text);
//通过手机号@群员
// OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
// at.setAtMobiles(Collections.singletonList("***"));
client.execute(request);
}
@SneakyThrows
public static String getKey() {
Long timestamp = System.currentTimeMillis();
String secret = "密钥";
String stringToSign = timestamp + "\n" + secret;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
System.out.println(sign);
return "×tamp=" + timestamp + "&sign=" + sign + "";
}
}
4.controller层
@RestController
@RequestMapping("/dingding")
public class DingDingController {
@Resource
private TestService testService;
@GetMapping("/test")
public String test() throws ApiException {
return testService.test();
}
}
5.service层
public interface TestService {
public String test() throws ApiException;
}
6.业务实现层
@Service
public class TestServiceImpl implements TestService {
@Autowired
private DingDing dingDing;
@Override
public String test() throws ApiException {
String message="helloword";
try {
dingDing.sendMessage(message);
}catch (Exception e){
return "发送失败";
}
return "发送成功!";
}
}
最后运行成功!
效果图:


699

被折叠的 条评论
为什么被折叠?



