记录调用企业微信推送消息

博客介绍了一个接单工具实时给业务人员发消息的场景,因邮箱发送速度慢,改用企业微信推送。还说明了使用Java实现企业微信消息推送的步骤,包括引入依赖、创建相关类,测试需用到企业微信账号秘钥,获取方法可百度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用场景说明:一个接单工具,需要实时的发送消息给到业务人员,本来是打算使用邮箱的,奈何邮箱的发送速度太慢,接口每十秒调用一次,但是邮箱发个邮件要18秒,效率太低,刚好公司有企业微信,就用企业微信做推送,速度快了很多,主要是比较简单,又能及时推送,手机又可以提示。
首先引入依赖:

 		<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

创建AccessToken类:

package com.shuzitengfei.ordertool.message;

import lombok.Data;
@Data
public class AccessToken {

    //获取到的access_token字符串
    private String accessToken;
    //有效时间(2h,7200s)
    private int expiresIn;

}

创建WeChatMessage类:

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

/**
 * @Author: ljp
 * @CreateDate: 2021/1/13 10:18
 */
public class WeChatMessage {
    //发送消息的类型
    private final static String MSG_TYPE = "text";
    //将消息发送给所有成员
    private final static String TO_PARTY = "@all";
    //获取企业微信的企业号,根据不同企业更改
    private final static String CORP_ID = "企业号";
    //获取企业应用的密钥,根据不同应用更改
    private final static String CORP_SECRET = "企业应用秘钥";
    //获取访问权限码URL
    private final static String ACCESS_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
    //创建会话请求URL
    private final static String CREATE_SESSION_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";

    //获取access_token
    public static AccessToken getAccessToken() {
        AccessToken token = new AccessToken();
        //访问微信服务器
        String url = ACCESS_TOKEN_URL + "?corpid=" + CORP_ID + "&corpsecret=" + CORP_SECRET;
        try {
            URL getUrl = new URL(url);
            //开启连接,并返回一个URLConnection对象
            HttpURLConnection http = (HttpURLConnection) getUrl.openConnection();
            http.setRequestMethod("GET");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            //将URL连接用于输入和输出,一般输入默认为true,输出默认为false
            http.setDoOutput(true);
            http.setDoInput(true);
            //进行连接,不返回对象
            http.connect();

            //获得输入内容,并将其存储在缓存区
            InputStream inputStream = http.getInputStream();
            int size = inputStream.available();
            byte[] buffer = new byte[size];
            inputStream.read(buffer);
            //将内容转化为JSON代码
            String message = new String(buffer, "UTF-8");
            JSONObject json = JSONObject.parseObject(message);
            //提取内容,放入对象
            token.setAccessToken(json.getString("access_token"));
            token.setExpiresIn(new Integer(json.getString("expires_in")));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回access_token
        return token;
    }

    /**
     * 企业接口向下属关注用户发送给微信消息
     *
     * @param toUser  成员ID列表
     * @param toParty 部门ID列表
     * @param toTag   标签ID列表
     * @param content 消息内容
     * @param safe    是否保密
     * @return
     */
    public void sendWeChatMessage(String toUser, String toParty, String toTag, String content, String safe) {
        //从对象中提取凭证
        AccessToken accessToken = getAccessToken();
        String ACCESS_TOKEN = accessToken.getAccessToken();
//        String url = CREATE_SESSION_URL + ACCESS_TOKEN;
        //请求串
        String sendUrl = CREATE_SESSION_URL + ACCESS_TOKEN;

        //封装发送消息请求JSON
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("{");
        stringBuffer.append("\"touser\":" + "\"" + toUser + "\",");
        stringBuffer.append("\"toparty\":" + "\"" + toParty + "\",");
        stringBuffer.append("\"totag\":" + "\"" + toTag + "\",");
        stringBuffer.append("\"msgtype\":" + "\"" + MSG_TYPE + "\",");
        stringBuffer.append("\"text\":" + "{");
        stringBuffer.append("\"content\":" + "\"" + content + "\"");
        stringBuffer.append("}");
        stringBuffer.append(",\"safe\":" + "\"" + safe + "\",");
        
        //这里的agentid每个人都是不一样的
        stringBuffer.append("\"agentid\":" + "\"" + "1000004" + "\",");
        
        stringBuffer.append("\"debug\":" + "\"" + "1" + "\"");
        stringBuffer.append("}");
        String json = stringBuffer.toString();
        System.out.println(json);

        try {
            URL postUrl = new URL(sendUrl);
            HttpURLConnection http = (HttpURLConnection) postUrl.openConnection();
            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            http.setDoOutput(true);
            http.setDoInput(true);
            // 连接超时30秒
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
            // 读取超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000");
            http.connect();

            //写入内容
            OutputStream outputStream = http.getOutputStream();
            outputStream.write(json.getBytes("UTF-8"));
            InputStream inputStream = http.getInputStream();
            int size = inputStream.available();
            byte[] jsonBytes = new byte[size];
            inputStream.read(jsonBytes);
            String result = new String(jsonBytes, "UTF-8");
            System.out.println("请求返回结果:" + result);

            //清空输出流
            outputStream.flush();
            //关闭输出通道
            outputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        WeChatMessage weChat = new WeChatMessage();
        weChat.sendWeChatMessage("Lucy", null, "", "测试消息","0");
    }

在main方法中可以做测试,需要用到企业微信的相关账号秘钥,怎么获取可以百度一下,资料还是蛮多的。在这里记录一下。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值