java+企业微信,java实现应用消息推送和24小时内的撤回

发布时间 2023-05-08 14:06:09作者: 长毛君吃面

1、java实现企业微信推送应用消息:

官方文档:开发前必读 - 文档 - 企业微信开发者中心 (qq.com) 动手能力强的直接看这个就能解决,点进去先看开发指南中的:基本概念介绍,获取access_token,再看基础的:消息推送。期间出现问题直接问度娘。

 

首先,需要获取相关企业微信信息:

corp_id:一个企业对应一个corp_id

agent_id:一个应用对应一个agent_id

app_secret:一个应用对应一个app_secret,与上面的agent_id是配对的

user_id:一个用户对应一个user_id,每个应用里都有指定的user_id,测试时需要保证应用中存在此用户

 

先新建一个空项目,再添加模块,手动添加lib文件夹,这里需要存放一个jar包:fastjson-1.2.28.jar

Maven Repository: com.alibaba » fastjson » 1.2.28 (mvnrepository.com) 下载 jar

然后去idea中把这个jar包放到项目中(右键点击这个.jar后选择添加为库),在项目中使用时(添加方式自选一):

(自动添加)直接输入以下代码:

import com.alibaba.fastjson.JSONObject;

(自动添加)选择将库添加到类路径:

 (手动添加)点击左上角"文件" --> "项目结构" --> "模块" --> "选择你的模块" --> 在右侧一栏选择"依赖" --> 点击"依赖"下方的"+",选择库,选择我们添加的jar包 -->点击"添加所选项",然后勾上它,点击"应用",点击"确定",然后就像上面一样import后使用。

 

以上都不要代码,是开发前的准备工作。接下来进行代码开发:

 1.1、获取access_token

//获取企业微信的企业号id
private final static String CORPID = "输入前期准备的corpid";
//获取企业应用的id
private final static String AGENTID = "输入前期准备的agentid";
//获取企业应用的密钥
private final static String CORPSECRET = "输入前期准备的corpsecret";
//获取访问权限码URL
private final static String ACCESS_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";

创建方法getAccessToken(){}

//访问微信服务器
String url = ACCESS_TOKEN_URL + "?corpid=" + CORPID + "&corpsecret=" + CORPSECRET;
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);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

其中的json就是请求返回的数据,里面有access_token和有效时间7200,

如果刚才的getAccessToken()方法定义为String,最后return时要注意改成String。

1.2、实现应用推送消息

//发送消息的类型
private final static String MSGTYPE = "text";
//创建会话请求URL
private final static String CREATE_SESSION_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
public void sendMessage(String toUser, String toParty, String toTag, String content, String safe) {
//从1、中的getAccessToken()方法中获取access_token(不在同一文件则new对象调用)
String ACCESS_TOKEN = getAccess_token();
//请求串
//String url = CREATE_SESSION_URL + ACCESS_TOKEN;

//封装发送消息请求JSON(请求报文)
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("{" + "\n");
stringBuffer.append("\"touser\":" + "\"" + toUser + "\"," + "\n");
stringBuffer.append("\"toparty\":" + "\"" + toParty + "\"," + "\n");
stringBuffer.append("\"totag\":" + "\"" + toTag + "\"," + "\n");
stringBuffer.append("\"msgtype\":" + "\"" + MSGTYPE + "\"," + "\n");
stringBuffer.append("\"text\":" + "{");
stringBuffer.append("\"content\":" + "\"" + content + "\"");
stringBuffer.append("}," + "\n");
stringBuffer.append("\"safe\":" + "\"" + safe + "\"," + "\n");
stringBuffer.append("\"agentid\":" + "\"" + AGENTID + "\"," + "\n");
stringBuffer.append("\"debug\":" + "\"" + "1" + "\"" + "\n");
stringBuffer.append("}");
String json = stringBuffer.toString();

try {
URL postUrl = new URL(url);
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"); //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();
}
}

(官方文档中都有)

toUser:指定接收消息的成员,成员ID列表(多个接收者用‘|’分隔,最多支持1000个)。特殊情况:指定为"@all",则向该企业应用的全部成员发送

toParty:指定接收消息的部门,部门ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为"@all"时忽略本参数

toTag:指定接收消息的标签,标签ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为"@all"时忽略本参数

MSGTYPE:消息类型,此时固定为:text(文本消息)

content:消息内容,最长不超过2048个字节,超过将截断(支持id转译)

safe:表示是否是保密消息,0表示可对外分享,1表示不能分享且内容显示水印,默认为0

AGENTID:企业应用的id,前期准备时有

 

好了,接下来只要调用 他就行了。

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
sendMsg(); //发送文字
}

public static void sendMsg(){
SendMessage s = new SendMessage();
s.sendMessage("你的toUser",
"",
"",
"你的content",
"0");
}
}

发送图片,文档等其他消息也是同样的思路,修改发送的请求报文等信息即可(需要提前上传素材,官方教程有接口可以直接用,也可以找度娘用java自己写,和发送消息差不多)

2.java实现企业微信撤回应用消息(限24小时)

24小时是官方限制,超过这个时间就不能撤回了。同样在上面给出的官方文档里也有对应教程。

撤回消息只需要2个信息,1个是access_token,还有1个是刚才发送消息后收到的返回报文,即代码中的 result

2.1、获取access_token

同上

2.2、实现撤回应用消息

//创建会话请求URL
private final static String CREATE_SESSION_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/recall?access_token=";
public void recallMsg(String msgid){
//获取access_token
String ACCESS_TOKEN = getAccess_token();
String url = CREATE_SESSION_URL + ACCESS_TOKEN;

//封装发送消息请求JSON
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("{");
stringBuffer.append("\"msgid\":\"" + msgid);
stringBuffer.append("\"");
stringBuffer.append("}");
String json = stringBuffer.toString();

try {
URL postUrl = new URL(url);
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("请求返回结果:");
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 class Main {
public static void main(String[] args) {
String result = readTxt.readTxt(); //这是我通过导出数据库后生成的txt文件,里面存放了很多msgid,你只需要换成自己的msgid即可。
recallMsg recallMsg = new recallMsg();
recallMsg.recallMsg(result); //recallMsh只能输入一条msgid,如果要撤回很多消息得做循环。
}
}

 

 

2023-05-08

----------------------------------------------------------------------------------

结束