Java程式碼實現向企業微信使用者傳送訊息
阿新 • • 發佈:2019-01-24
公司內部交流使用的企業微信,最近專案中要實現向員工傳送企業微信通知,於是看了下企業微信的api,簡單實現了下:
1. 其實就是一個HTTP請求,如下
請求方式:POST(HTTPS)
請求地址: https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN
文字訊息請求引數例項如下
-
{ "touser" : "UserID1|UserID2|UserID3",//使用者的ID, "toparty" : "PartyID1|PartyID2",//部門id "totag" : "TagID1 | TagID2",//標籤id "msgtype" : "text",//訊息型別 "agentid" : 1,//應用的ID,比如時公告還是通知什麼一類的,可參考企業微信開發者文件 "text" : { //型別和內容 "content" : "你的快遞已到,請攜帶工卡前往郵件中心領取。\n出發前可檢視<a href=\"http://work.weixin.qq.com\">郵件中心視訊實況</a>,聰明避開排隊。" }, "safe":0//是否保密資訊 } //其中 touser、toparty、totag不能同時為空
其他如圖片型別,語音則可以參考開發者文件中的型別對應設定:企業微信-開發者文件
pom依賴
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.2</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.5</version> </dependency>
2. 獲取access_token
用到的UrlData類和WeChatData
import org.springframework.stereotype.Component; @Component public class UrlData { String corpId; String corpSecret; String getTokenUrl; String sendMessageUrl; public String getCorpId() { return corpId; } public void setCorpId(String corpId) { this.corpId = corpId; } public String getCorpSecret() { return corpSecret; } public void setCorpSecret(String corpSecret) { this.corpSecret = corpSecret; } public void setGetTokenUrl(String corpid, String corpsecret) { this.getTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret; } public String getGetTokenUrl() { return getTokenUrl; } public String getSendMessageUrl() { sendMessageUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="; return sendMessageUrl; } }
package com.lls.it.ldapapi.entity;
import org.springframework.stereotype.Component;
@Component
public class WeChatData {
String touser;
String msgtype;
int agentid;
Object text;
public Object getText() {
return text;
}
public void setText(Object text) {
this.text = text;
}
public String getMsgtype() {
return msgtype;
}
public void setMsgtype(String msgtype) {
this.msgtype = msgtype;
}
public int getAgentid() {
return agentid;
}
public void setAgentid(int agentid) {
this.agentid = agentid;
}
public String getTouser() {
return touser;
}
public void setTouser(String touser) {
this.touser = touser;
}
}
請求方式:GET(HTTPS)
請求URL:https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRECT
注:此處標註大寫的單詞ID和SECRET,為需要替換的變數,根據實際獲取值更新。
public String getToken(String corpId, String corpSecret) throws IOException {
SendMsgService sw = new SendMsgService();
UrlData uData = new UrlData();
uData.setGetTokenUrl(corpId, corpSecret);
String resp = sw.toAuth(uData.getGetTokenUrl());//就是按照GET方式拼接了字串得到url
Map<String, Object> map = gson.fromJson(resp,
new TypeToken<Map<String, Object>>() {
}.getType());
System.out.println(map);
return map.get("access_token").toString();
}
protected String toAuth(String Get_Token_Url) throws IOException {
httpClient = HttpClients.createDefault();
httpGet = new HttpGet(Get_Token_Url);
CloseableHttpResponse response = httpClient.execute(httpGet);
System.out.println(response.toString());
String resp;
try {
HttpEntity entity = response.getEntity();
System.out.println(response.getAllHeaders());
resp = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);
} finally {
response.close();
}
return resp;
}
3. POST請求,根據上一步得到的token,傳送post請求
應用支援推送文字、圖片、視訊、檔案、圖文等型別。
請求方式:POST(HTTPS)
請求地址: https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN
引數說明:
引數 | 是否必須 | 說明 |
---|---|---|
access_token | 是 | 呼叫介面憑證 |
請求body就是文章開頭的json資料(text型別)
程式碼如下:
/**
* 建立POST BODY
*/
private String createPostData(String touser, String msgtype, int agent_id, String contentKey, String contentValue) {
WeChatData weChatData = new WeChatData();
weChatData.setTouser(touser);
weChatData.setAgentid(agent_id);
weChatData.setMsgtype(msgtype);
Map<Object, Object> content = new HashMap<Object, Object>();
content.put(contentKey, contentValue + "\n--------\n" + df.format(new Date()));
weChatData.setText(content);
System.out.println(gson.toJson(weChatData));
return gson.toJson(weChatData);
}
/**
* POST請求
*/
private String post(String charset, String contentType, String url, String data, String token) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
httpPost = new HttpPost(url + token);
httpPost.setHeader(CONTENT_TYPE, contentType);
httpPost.setEntity(new StringEntity(data, charset));
CloseableHttpResponse response = httpclient.execute(httpPost);
String resp;
try {
HttpEntity entity = response.getEntity();
resp = EntityUtils.toString(entity, charset);
EntityUtils.consume(entity);
} finally {
response.close();
}
return resp;
}
4. 呼叫方法請求傳送
private CloseableHttpClient httpClient;
private HttpPost httpPost;//用於提交登陸資料
private HttpGet httpGet;//用於獲得登入後的頁面
public static final String CONTENT_TYPE = "Content-Type";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//
private static Gson gson = new Gson();
public void sendTextMesg(String toUser, String contentValue) throws IOException {
String token = getToken("Your_corpId", "Your_corpSecret");
String postData = createPostData(toUser, "text", 1000002, "content", contentValue);
String response = post("utf-8", SendMsgService.CONTENT_TYPE, (new UrlData()).getSendMessageUrl(), postData, token);
System.out.println("獲取到的token======>" + token);
System.out.println("請求資料======>" + postData);
System.out.println("傳送微信的響應資料======>" + response);
}
其實企業微信開發者文件就是給我們提供了介面,我們要做的只是封裝好我們的請求json,請求對應的介面就可以了。