import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import java.io.IOException;
public class DingTalkRobot {
// 钉钉机器人Webhook
private static final String WEBHOOK_TOKEN = "https://oapi.dingtalk.com/robot/send?access_token=XXXXXXXXXXXXXXX";
/**
* 发送文本消息
*
* @param content 消息内容
*/
public static void sendTextMessage(String content) {
JSONObject json = new JSONObject();
json.put("msgtype", "text");
JSONObject text = new JSONObject();
text.put("content", content);
json.put("text", text);
send(json.toJSONString());
}
/**
* 发送Markdown消息
*
* @param title 消息标题
* @param content 消息内容
*/
public static void sendMarkdownMessage(String title, String content) {
JSONObject json = new JSONObject();
json.put("msgtype", "markdown");
JSONObject markdown = new JSONObject();
markdown.put("title", title);
markdown.put("text", content);
json.put("markdown", markdown);
send(json.toJSONString());
}
/**
* 发送消息
*
* @param message 消息体
*/
private static void send(String message) {
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(mediaType, message);
Request request = new Request.Builder()
.url(WEBHOOK_TOKEN)
.post(body)
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
System.out.println("发送成功");
} else {
System.out.println("发送失败:" + response.code() + " " + response.message());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}