java发送企业微信群

一、修改pom.xml

<dependency>
   <groupId>com.squareup.okhttp3</groupId>
   <artifactId>okhttp</artifactId>
   <version>3.14.9</version>
</dependency>
<dependency>
   <groupId>commons-codec</groupId>
   <artifactId>commons-codec</artifactId>
   <version>1.10</version>
</dependency>

 二、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 okhttp3.*;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Slf4j
public class WeComPushUtil {


	private static final String SECRET = "96b1f94b-eadc-441c-b8cb-87a93d7a4904hlw";

	/**
	 * 配置企业微信的webhook
	 * https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=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","铁塔","大火熊熊燃气啊");
	}

	/**
	 *
	 * @param token   企业微信机器人token
	 * @param warningName   告警名称
	 * @param level 告警级别
	 * @param deviceInfo  设备信息
	 * @param content  告警内容
	 */
	public static void sendGroup(String token,String warningName,String level,String deviceInfo,String content){
		try {
			JSONObject reqBody = getReqBody(String.format(dingTemplate, warningName, level, deviceInfo, content, format1.format(new Date())));
			callWeChatBot(reqBody.toString(),token);
		}catch (Exception e){

		}
	}

	/**
	 * 发送MarKDown消息
	 *
	 * @param msg 需要发送的消息
	 * @return
	 * @throws Exception
	 */
	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);
		reqBody.put("safe", 0);
		return reqBody;

	}
	/**
	 * 调用群机器人
	 *
	 * @param reqBody 接口请求参数
	 * @throws Exception 可能有IO异常
	 */
	public static String callWeChatBot(String reqBody,String botUrl) throws Exception {
		log.info("请求参数:" + reqBody);

		// 构造RequestBody对象,用来携带要提交的数据;需要指定MediaType,用于描述请求/响应 body 的内容类型
		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))) {
			log.info("向群发送消息成功!");
		} else {
			log.info("请求失败!");
			// 发送错误信息到群
			sendTextMsg("群机器人推送消息失败,错误信息:\n" + respMsg);
		}
		return respMsg;
	}

	/**
	 * @param body 携带需要提交的数据
	 * @param url  请求地址
	 * @return
	 * @throws Exception
	 */
	public static String okHttp(RequestBody body, String url) throws Exception {
		// 构造和配置OkHttpClient
		OkHttpClient client;
		client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS) // 设置连接超时时间
				.readTimeout(20, TimeUnit.SECONDS) // 设置读取超时时间
				.build();

		// 构造Request对象
		Request request = new Request.Builder().url(url).post(body).addHeader("cache-control", "no-cache") // 响应消息不缓存
				.build();

		// 构建Call对象,通过Call对象的execute()方法提交异步请求
		Response response = null;
		try {
			response = client.newCall(request).execute();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 请求结果处理
		byte[] datas = response.body().bytes();
		String respMsg = new String(datas);
		log.info("返回结果:" + respMsg);

		return respMsg;
	}
	/**
	 * 发送文字消息
	 *
	 * @param msg 需要发送的消息
	 * @return
	 * @throws Exception
	 */
	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);
		reqBody.put("safe", 0);

		return callWeChatBot(reqBody.toString(),SECRET);
	}

}

### 使用Java API 向企业微信发送消息 为了通过Java程序调用企业微信API并成功发送消息,开发者需遵循特定的流程。此过程涉及获取`access_token`以及利用该令牌调用具体的消息发送接口。 #### 获取Access Token 访问企业微信API的第一步是获得`access_token`,这是用于验证请求合法性的凭证。可以通过HTTP GET方法向指定URL发起请求来取得这个token: ```http GET https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRET ``` 其中`corpid`为企业ID而`corpsecret`则是应用密钥[^2]。 一旦收到响应,解析JSON格式的数据提取出`access_token`字段值以便后续使用。 #### 构建消息体 构建要发送的信息内容作为POST请求的一部分。对于文本类型的通知来说,其结构如下所示: ```json { "touser": "@all", "msgtype": "text", "agentid": AGENT_ID, "text": { "content": "您的订单已发货" }, "safe": 0 } ``` 这里`touser`参数指定了接收者;如果设置成"@all"则表示全体成员都会接收到通知。`agentid`代表应用程序标识符,它由创建自定义应用时分配而来。 #### 发送消息企业微信聊 最后一步就是实际执行发送动作了。这同样依赖于HTTPS POST请求,不过这次的目标地址有所变化,并且需要附带之前得到的`access_token`: ```http POST https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=TOKEN ``` 将上述准备好的JSON对象序列化为字符串形式附加到请求主体内即可完成整个操作。 下面给出一段完整的Java代码示例展示如何实现以上步骤: ```java import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class WeChatMessageSender { private static final String CORP_ID = "your_corp_id"; private static final String SECRET = "your_secret_key"; public static void main(String[] args) throws IOException { // Step 1: Get access token from wechat server. String accessTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + CORP_ID + "&corpsecret=" + SECRET; HttpURLConnection connection = (HttpURLConnection)new URL(accessTokenUrl).openConnection(); InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder responseBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null){ responseBuilder.append(line); } String jsonResponse = responseBuilder.toString(); // Parse JSON to get the actual value of 'access_token'. int startIndex = jsonResponse.indexOf("\"access_token\":\"") + "\"access_token\":\"".length(); int endIndex = jsonResponse.indexOf('\"', startIndex); String accessToken = jsonResponse.substring(startIndex, endIndex); // Prepare message content as a JSON string. String jsonPayload = "{\n" + " \"touser\": \"@all\",\n" + " \"msgtype\": \"text\",\n" + " \"agentid\": YOUR_AGENT_ID,\n" + " \"text\": {\n" + " \"content\": \"Hello everyone!\"\n" + " },\n" + " \"safe\": 0\n" + "}"; // Send the prepared message using obtained access token. sendWeChatMessage(jsonPayload, accessToken); } private static void sendWeChatMessage(String payload, String accessToken) throws IOException { String sendMessageUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken; HttpURLConnection conn = (HttpURLConnection)new URL(sendMessageUrl).openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Triggers POST. try (OutputStream os = conn.getOutputStream()){ byte[] input = payload.getBytes("utf-8"); os.write(input, 0, input.length); } finally { conn.disconnect(); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值