1.创建发送消息类,mess为传入的消息变量信息,xxxxxx是企业微信机器人的key
public static class SendMessage {
public static String WEBHOOK_TOKEN = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxxx";
public void send(String mess) throws IOException {
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(WEBHOOK_TOKEN);
httppost.addHeader("Content-Type", "application/json; charset=utf-8");
//构建一个json格式字符串textMsg,其内容是接收方需要的参数和消息内容
String textMsg = "{\"msgtype\":\"text\",\"text\":{\"content\":\"磁盘超过70预警测试,请关注:"+mess+"\",\"mentioned_mobile_list\":[\"联系人1\",\"联系人2\",\"联系人3\"]},\"safe\":\"0\"}";
StringEntity se = new StringEntity(textMsg, "utf-8");
httppost.setEntity(se);
HttpResponse response1 = httpclient.execute(httppost);
if (response1.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(response1.getEntity(), "utf-8");
System.out.println(result);
}
}
}
2.在主函数中获取Mess变量信息,一般是从接口中获取到的数据。
利用fastjson 获取数据。
以下用自定义数据测试。
HashMap<String,Double> data_map=new HashMap<>();
data_map.put('销售额',278.02);
调用发送消息类
SendMessage sendme = new SendMessage();
sendme.send(data_map.toString());
3.运行成功