企业微信需要一个token做为唯一调用凭证 首先咱们需要获取一下企业微信的token 直接上代码
public static void main(String[] args) {
String corpid = "****";//企业ID
String corpsecret = "*****";//应用密钥
try {
String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret;
URL u = new URL(url);
HttpsURLConnection huconn = (HttpsURLConnection) u.openConnection();
BufferedReader in = null;
StringBuilder result = new StringBuilder();
huconn.connect();
in = new BufferedReader(new InputStreamReader(huconn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
if (in != null) {
in.close();
}
System.out.println(result);
JSONObject myJsonObject = new JSONObject();
myJsonObject = JSONObject.fromObject(result.toString());
String token = myJsonObject.getString("access_token");
System.out.println(token);
// 打印token
send(token);
} catch (Exception e) {
e.printStackTrace();
}
}
获取到唯一凭证以后就可以根据不同的模板推送不同的消息了 下来请看代码
public static void send(String token){
String markdown = "****"
+ "\n>**事项详情** "
+ "\n>指标层级:<font color=\"info\">一级风险预警</font> "
+ "\n>指标名称:<font color=\"info\">安全预警指标值</font> "
+ "\n>预警等级:黄色预警"
+ "\n>当前值:1.5"
+ "\n>预警值:1.2"
+ "\n>处理状态:未处理";
JSONObject params = new JSONObject();
params.put("touser", "****");//用户ID
params.put("msgtype", "markdown");
params.put("toparty", "");
params.put("totag", "");
params.put("agentid", "****");//应用ID
JSONObject mytext = new JSONObject();
mytext.put("content", markdown);
params.put("markdown", mytext);
params.put("enable_duplicate_check", 0);
params.put("duplicate_check_interval", 1800);
try {
String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+ token;
System.out.println("url-----------"+url);
URL u = new URL(url);
HttpsURLConnection http = (HttpsURLConnection) u.openConnection();
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type","application/json;charset=UTF-8");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//
// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //
// 读取超时30秒
http.connect();
OutputStream os = http.getOutputStream();
os.write(params.toString().getBytes("UTF-8"));// 传入参数
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String result = new String(jsonBytes, "UTF-8");//回调函数
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
简单明了 。