Java开发企业微信群机器人发送markdown消息
企业微信群机器人配置
参考网址
使用Java发送markdown消息
注意: 本代码仅依赖 com.google.gson.Gson , 其他均JDK1.8原生类.
消息应答结果实体
/**
* 企业微信群机器人发送消息应答结果.<br>
*/
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;
}
}
核心代码
/**
* 发送相应的Markdown内容到对应key的机器人.
*
* @param key 机器人key
* @param markdown Markdown内容
* @return
*/
public final WeComRobotResponse sendMarkdown(@Nullable final String key, @Nonnull final String markdown) {
if (markdown.isEmpty()) {
return null;
}
/** 拼接数据, 格式: {'msgtype': 'markdown', 'markdown': {'content': 'Markdown实际内容.'}} */
Map<String, String> data = new HashMap<>();
data.put("content", markdown);
Map<String, Object> 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.