package com.cim.idm.utils; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import java.io.IOException; public class DingTalkSender { private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); public static void sendTextMessage(String accessToken, String agentId, String userId, String chatId, String message) throws IOException { OkHttpClient client = new OkHttpClient(); String json = "{\"agent_id\":\"" + agentId + "\",\"userid_list\":\"" + userId + "\",\"deptid_list\":[\"" + userId + "\"],\"chatid\":\"" + chatId + "\",\"msg\":{\"msgtype\": \"text\",\"text\": {\"content\": \"" + message + "\"}}}"; RequestBody body = RequestBody.create(json, JSON); Request request = new Request.Builder() .url("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=" + accessToken) .post(body) .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); } } public static void main(String[] args) { try { String accessToken = DingTalkUtils.getAccessToken(); String agentId = "3206304704"; // 如果API调用不需要,则忽略此参数 String chatId = "095452471826097763,02000826241189265"; // 账号 String message = "Hello, this is a test message from Java!"; //发送内容 sendTextMessage(accessToken, agentId, chatId, chatId,message); } catch (IOException e) { e.printStackTrace(); } } }