【Java开发】Java实现调用微信机器人,发送企业微信通知

时间:2025-02-19 21:31:46
package TEST3; import org.apache.http.HttpStatus; 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.io.IOException; import java.util.Scanner; public class SendMsg2 { public static void main(String[] args) throws IOException { Scanner scan = new Scanner(System.in); System.out.println("请输入要发送的消息内容:"); String content = scan.nextLine(); sendText(content); } //消息体 //拼接json字符串 //可以进行其他的拓展 比如卡片形式、图片形式等 public static String sendText(String content) throws IOException { content = "{\n" + " \"msgtype\": \"text\",\n" + " \"text\": {\n" + " \"content\": \"" + content + "\"\n" + " }\n" + "}"; return send(content); } public static String send(String textMsg) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault();//实例化对象 HttpPost httpPost = new HttpPost("/cgi-bin/webhook/send?key=33d69c01-d962-478b-8945-288e00e2abf2");//url地址 httpPost.addHeader("Content-Type", "application/json; charset=utf-8");//发送消息的格式; StringEntity se = new StringEntity(textMsg, "utf-8");//编码转换 httpPost.setEntity(se); CloseableHttpResponse response = httpClient.execute(httpPost); //发送成功接收返回值 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result = EntityUtils.toString(response.getEntity(), "utf-8"); System.out.println("发送微信机器人消息成功 " + result); return result; } else { System.out.println("发送微信机器人消息失败"); } // 关闭 httpClient.close(); response.close(); return "发送微信机器人消息失败"; } }