一、修改pom.xml
com.squareup.okhttp3
okhttp
3.14.9
commons-codec
commons-codec
1.10
二、java代码
package com.sdmktech.mep.energy.monitor.utils;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
public class WeComPushUtil {
private static final String SECRET = "96b1f94b-eadc-441c-b8cb-87a93d7a4904hlw";
private static final String WEBHOOK = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=";
private static final String dingTemplate = "**告警名称** : %s\n\n**告警级别** : %s\n\n**设备信息** : %s\n\n" +
"**告警内容** : %s\n\n**告警时间** : %s\n\n";
private static SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) {
sendGroup(SECRET,"火灾","S2","铁塔","大火熊熊燃气啊");
public static void sendGroup(String token,String warningName,String level,String deviceInfo,String content){
JSONObject reqBody = getReqBody(String.format(dingTemplate, warningName, level, deviceInfo, content, format1.format(new Date())));
callWeChatBot(reqBody.toString(),token);
public static JSONObject getReqBody(String msg) throws Exception {
JSONObject markdown = new JSONObject();
markdown.put("content", msg);
JSONObject reqBody = new JSONObject();
reqBody.put("msgtype", "markdown");
reqBody.put("markdown", markdown);
public static String callWeChatBot(String reqBody,String botUrl) throws Exception {
log.info("请求参数:" + reqBody);
MediaType contentType = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(contentType, reqBody);
String respMsg = okHttp(body, WEBHOOK+botUrl);
if ("0".equals(respMsg.substring(11, 12))) {
sendTextMsg("群机器人推送消息失败,错误信息:\n" + respMsg);
public static String okHttp(RequestBody body, String url) throws Exception {
client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
Request request = new Request.Builder().url(url).post(body).addHeader("cache-control", "no-cache")
Response response = null;
response = client.newCall(request).execute();
} catch (IOException e) {
byte[] datas = response.body().bytes();
String respMsg = new String(datas);
log.info("返回结果:" + respMsg);
public static String sendTextMsg(String msg) throws Exception {
JSONObject text = new JSONObject();
text.put("content", msg);
JSONObject reqBody = new JSONObject();
reqBody.put("msgtype", "text");
reqBody.put("text", text);
return callWeChatBot(reqBody.toString(),SECRET);