package com.ruzhoukj.sms.common; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.util.Arrays; public class WeChatRobotSender { private final String webhookUrl; public WeChatRobotSender(String webhookUrl) { this.webhookUrl = webhookUrl; } public void sendTextMessage(String content, String[] mentionedList, String[] mentionedMobileList) throws Exception { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(this.webhookUrl); httpPost.setHeader("Content-Type", "application/json; charset=utf-8"); // 构建JSON请求体 String jsonMsg = buildTextMessageJson(content, mentionedList, mentionedMobileList); System.out.println("请求体: " + jsonMsg); StringEntity entity = new StringEntity(jsonMsg, "UTF-8"); httpPost.setEntity(entity); // 发送请求并获取响应 try (CloseableHttpResponse response = httpClient.execute(httpPost)) { String responseBody = EntityUtils.toString(response.getEntity()); System.out.println("响应结果: " + responseBody); } } } private String buildTextMessageJson(String content, String[] mentionedList, String[] mentionedMobileList) { // 使用字符串拼接或Json库(如Jackson、Gson)构建JSON更稳妥,此处为示例 StringBuilder json = new StringBuilder(); json.append("{"); json.append("\"msgtype\": \"text\","); json.append("\"text\": {"); json.append("\"content\": \"").append(content).append("\""); if (mentionedList != null && mentionedList.length > 0) { json.append(", \"mentioned_list\": ").append(Arrays.toString(mentionedList).replace("[", "[\"").replace("]", "\"]").replace(", ", "\", \"")); } if (mentionedMobileList != null && mentionedMobileList.length > 0) { json.append(", \"mentioned_mobile_list\": ").append(Arrays.toString(mentionedMobileList).replace("[", "[\"").replace("]", "\"]").replace(", ", "\", \"")); } json.append("}"); json.append("}"); return json.toString(); } public static void main(String[] args) { String webhookUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=04c5f353-33a7-4cb0-8d00-798dee5df953"; WeChatRobotSender sender = new WeChatRobotSender(webhookUrl); try { // 发送文本消息,并@指定手机号的成员和所有人 // sender.sendTextMessage("这个月的运维工作记得做", null, new String[]{"19825040761", "@all"}); // sender.sendTextMessage("这个月的运维工作记得做", null, new String[]{"19825040761"}); // sender.sendTextMessage("这个月的运维工作记得做", null, new String[]{"19825040761"}); } catch (Exception ignored) { } } }