企业微信机器人消息发送

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName QIYeWxUtil 
 * @Author ZhangRF
 * @CreateDate 2021/10/20
 * @Decription  企业微信机器人消息发送工具类
 */
@Slf4j
public class QIYeWxUtil {

    /**
     * 企业微信消息推送,最大长度5120字节
     *
     * @param content  内容
     * @param profile    环境
     * @param webHookAddress  机器人地址
     * @return
     */
    public static boolean sendMessage(String content, String profile, String webHookAddress) {
        content = StringUtil.subStringByBytes(content, 0, 5120);
        String msgtype = "text";
        content = "【项目名称】【" + profile + "】" + content;
        String atMobiles = "[手机号]";
        String isAtAll = "false";

        JSONObject message = new JSONObject();
        message.put("msgtype", msgtype);
        JSONObject textJsonObject = new JSONObject();
        textJsonObject.put("content", content);
        message.put("text", textJsonObject);
        JSONObject atJsonObject = new JSONObject();
        atJsonObject.put("atMobiles", atMobiles);
        atJsonObject.put("isAtAll", isAtAll);
        message.put("at", atJsonObject);

        OkHttpClient client = new OkHttpClient.Builder()
                // 设置连接超时时间
                .connectTimeout(10, TimeUnit.SECONDS)
                // 设置读取超时时间
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
        MediaType contentType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(contentType, message.toJSONString());
        Request request = new Request.Builder().url(webHookAddress).post(body).addHeader("cache-control", "no-cache").build();
        try {
            Response response = client.newCall(request).execute();
            byte[] datas = response.body().bytes();
            String respMsg = new String(datas);
            JSONObject resultJSON = JSONObject.parseObject(respMsg);
            if (resultJSON.getIntValue("errcode") == 0) {
//                log.info("消息发送成功!");
                return true;
            }
            log.error("消息发送失败, 错误信息如下: {}", resultJSON.getString("errmsg"));
            return false;
        } catch (IOException e) {
            log.error("消息发送失败, 异常信息如下: {}", e.getMessage());
            return false;
        }
    }
}
原文地址:https://www.cnblogs.com/zhangrongfei/p/15667293.html