栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java开发企业微信群机器人发送markdown消息

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java开发企业微信群机器人发送markdown消息

Java开发企业微信群机器人发送markdown消息
  • 企业微信群机器人配置
  • 使用Java发送markdown消息
    • 消息应答结果实体
    • 核心代码
  • 完整Java工具类
    • 完整Java工具类
    • Demo01
    • Demo02
  • sendMarkdown 简化

企业微信群机器人配置

参考网址

  • 群机器人配置说明
  • 发送应用消息
使用Java发送markdown消息
  • 注意: 本代码仅依赖 com.google.gson.Gson , 其他均JDK1.8原生类.
消息应答结果实体
public final class WeComRobotResponse {
    private int errcode;
    private String errmsg;
    public int getErrcode() {
        return errcode;
    }
    public void setErrcode(int errcode) {
        this.errcode = errcode;
    }
    public String getErrmsg() {
        return errmsg;
    }
    public void setErrmsg(String errmsg) {
        this.errmsg = errmsg;
    }
}
核心代码
public final WeComRobotResponse sendMarkdown(@Nullable final String key, @Nonnull final String markdown) {
    if (markdown.isEmpty()) {
        return null;
    }
    
    Map data = new HashMap<>();
    data.put("content", markdown);
    Map json = new HashMap<>();
    json.put("msgtype", "markdown");
    json.put("markdown", data);
    byte[] bytes = new Gson().toJson(json).getBytes(StandardCharsets.UTF_8);
    // 创建链接
    HttpURLConnection httpConnection = null;
    try {
        URL url = new URL(String.format(TARGET_URL, Optional.ofNullable(key).orElseGet(() -> defaultKey)));
        httpConnection = HttpURLConnection.class.cast(url.openConnection());
        httpConnection.setRequestMethod("POST");
        httpConnection.addRequestProperty("Content-Type", "application/json;charset=UTF-8");
        httpConnection.setRequestProperty("Accept", "application/json");
        httpConnection.setRequestProperty("Content-Length", String.valueOf(bytes.length));
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);
        httpConnection.setUseCaches(false);
        httpConnection.connect();
    } catch (IOException e) {
        LOGGER.error(e.getClass().getName(), e);
        return null;
    }
    // 推送数据
    try (OutputStream out = httpConnection.getOutputStream();) {
        out.write(bytes);
        out.flush();
    } catch (IOException e) {
        LOGGER.error(e.getClass().getName(), e);
        return null;
    }
    // 请求失败
    try {
        if (200 != httpConnection.getResponseCode()) {
            return null;
        }
    } catch (IOException e) {
        LOGGER.error(e.getClass().getName(), e);
        return null;
    }
    // 接收数据
    String response = null;
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream(1 << 5); InputStream isr = httpConnection.getInputStream();) {
        byte[] buffer = new byte[512];
        int n = 0;
        while ((n = isr.read(buffer)) >= 0) {
            baos.write(buffer, 0, n);
        }
        response = new String(baos.toByteArray(), StandardCharsets.UTF_8);
    } catch (IOException e) {
        LOGGER.error(e.getClass().getName(), e);
        return null;
    }
    // 断开连接
    httpConnection.disconnect();
    LOGGER.info("We Com Send Message State :: {}", response);
    return new Gson().fromJson(response, WeComRobotResponse.class);
}
完整Java工具类 完整Java工具类
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;


@Order(value = Integer.MIN_VALUE)
@Component
public class WeComRobotUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(WeComRobotUtils.class);
    private static final String TARGET_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=%s";
    @Value(value = "${wecom.robot.key:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}")
    private String defaultKey;
    
    public static final class Markdown {
        private static final String PROPS_FORMAT = "> %s: %sn";
        private String title;
        private List props = new ArrayList<>(1 << 5);
        private String footer;
        private static final class ColorValue {
            private String label;
            private String value;
            private String color;
            public static final ColorValue of(final String label, final String value) {
                return new ColorValue(label, value, "#747474");
            }
            public static final ColorValue of(final String label, final String value, final String color) {
                return new ColorValue(label, value, color);
            }
            private ColorValue(String label, String value, String color) {
                this.label = label;
                this.value = value;
                this.color = color;
            }
            public String getLabel() {
                return label;
            }
            public String getValue() {
                return value;
            }
            public String getColor() {
                return color;
            }
        }
        public static final Markdown of(final String title) {
            return new Markdown(title);
        }
        public Markdown(String title) {
            this.title = title;
        }
        public String getTitle() {
            return title;
        }
        public List getProps() {
            return props;
        }
        public String getFooter() {
            return footer;
        }
        public Markdown setFooter(final String footer) {
            this.footer = footer;
            return this;
        }
        public Markdown addProp(final String label, final String value) {
            this.getProps().add(ColorValue.of(label, value));
            return this;
        }
        public Markdown addProp(final String label, final String value, final String color) {
            this.getProps().add(ColorValue.of(label, value, color));
            return this;
        }
        @Override
        public String toString() {
            StringBuilder out = new StringBuilder(1 << 8);
            out.append(this.getTitle()).append(":").append("nn"); // 标题
            this.getProps().forEach(item -> out.append(String.format(PROPS_FORMAT, item.getLabel(), item.getColor(), item.getValue())));
            out.append("n").append(Optional.ofNullable(this.getFooter()).orElseGet(() -> "")); // 结尾
            return out.toString();
        }
    }
    
    public final class WeComRobotResponse {
        private int errcode;
        private String errmsg;
        public int getErrcode() {
            return errcode;
        }
        public void setErrcode(int errcode) {
            this.errcode = errcode;
        }
        public String getErrmsg() {
            return errmsg;
        }
        public void setErrmsg(String errmsg) {
            this.errmsg = errmsg;
        }
    }
    
    public final boolean sendMarkdownAndCheck(@Nonnull final String markdown) {
        return WeComRobotUtils.isOk(this.sendMarkdown(defaultKey, markdown));
    }
    
    public final boolean sendMarkdownAndCheck(@Nullable final String key, @Nonnull final String markdown) {
        return WeComRobotUtils.isOk(this.sendMarkdown(key, markdown));
    }
    
    public final WeComRobotResponse sendMarkdown(@Nonnull final String markdown) {
        return this.sendMarkdown(defaultKey, markdown);
    }
    
    public final WeComRobotResponse sendMarkdown(@Nullable final String key, @Nonnull final String markdown) {
        if (markdown.isEmpty()) {
            return null;
        }
        
        Map data = new HashMap<>();
        data.put("content", markdown);
        Map json = new HashMap<>();
        json.put("msgtype", "markdown");
        json.put("markdown", data);
        byte[] bytes = new Gson().toJson(json).getBytes(StandardCharsets.UTF_8);
        // 创建链接
        HttpURLConnection httpConnection = null;
        try {
            URL url = new URL(String.format(TARGET_URL, Optional.ofNullable(key).orElseGet(() -> defaultKey)));
            httpConnection = HttpURLConnection.class.cast(url.openConnection());
            httpConnection.setRequestMethod("POST");
            httpConnection.addRequestProperty("Content-Type", "application/json;charset=UTF-8");
            httpConnection.setRequestProperty("Accept", "application/json");
            httpConnection.setRequestProperty("Content-Length", String.valueOf(bytes.length));
            httpConnection.setDoInput(true);
            httpConnection.setDoOutput(true);
            httpConnection.setUseCaches(false);
            httpConnection.connect();
        } catch (IOException e) {
            LOGGER.error(e.getClass().getName(), e);
            return null;
        }
        // 推送数据
        try (OutputStream out = httpConnection.getOutputStream();) {
            out.write(bytes);
            out.flush();
        } catch (IOException e) {
            LOGGER.error(e.getClass().getName(), e);
            return null;
        }
        // 请求失败
        try {
            if (200 != httpConnection.getResponseCode()) {
                return null;
            }
        } catch (IOException e) {
            LOGGER.error(e.getClass().getName(), e);
            return null;
        }
        // 接收数据
        String response = null;
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream(1 << 5); InputStream isr = httpConnection.getInputStream();) {
            byte[] buffer = new byte[512];
            int n = 0;
            while ((n = isr.read(buffer)) >= 0) {
                baos.write(buffer, 0, n);
            }
            response = new String(baos.toByteArray(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            LOGGER.error(e.getClass().getName(), e);
            return null;
        }
        // 断开连接
        httpConnection.disconnect();
        LOGGER.info("We Com Send Message State :: {}", response);
        return new Gson().fromJson(response, WeComRobotResponse.class);
    }
    
    public static final boolean isOk(WeComRobotResponse res) {
        return Objects.nonNull(res) && 0 == res.getErrcode();
    }
}
Demo01
@org.springframework.beans.factory.annotation.Autowired
private WeComRobotUtils wecomRobot;
......
String markdown = WeComRobotUtils.Markdown.of("Markdown标题")
     .addProp("Label01", "Label01-Value", "red")
     .addProp("Label02", "Label02-Value")
     .addProp("时间", LocalDateTime.now().toString(), "#027e7e")
     .setFooter("请尽快处理.")
     .toString();
wecomRobot.sendMarkdown(markdown); 或 wecomRobot.sendMarkdownAndCheck(markdown);
或者
String key = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
wecomRobot.sendMarkdown(key, markdown); 或 wecomRobot.sendMarkdownAndCheck(key, markdown);
Demo02
@org.springframework.beans.factory.annotation.Autowired
private WeComRobotUtils wecomRobot;
......
String markdown = "Markdown标题:nn>Label01: Label01-ValuenLabel02: Label02-Valuenn请尽快处理.";
wecomRobot.sendMarkdown(markdown); 或 wecomRobot.sendMarkdownAndCheck(markdown);
或者
String key = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
wecomRobot.sendMarkdown(key, markdown); 或 wecomRobot.sendMarkdownAndCheck(key, markdown);
......
sendMarkdown 简化
import org.springframework.web.client.RestTemplate;

public final WeComRobotResponse sendMarkdown(@Nullable final String key, @Nonnull final String markdown) {
    
    Map data = new HashMap<>();
    data.put("content", markdown);
    Map json = new HashMap<>();
    json.put("msgtype", "markdown");
    json.put("markdown", data);
    
    String url = String.format(TARGET_URL, Optional.ofNullable(key).orElseGet(() -> defaultKey));
    
    return new RestTemplate().postForEntity(url, json, WeComRobotResponse.class).getBody();
}
请多多指教
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/425254.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号