Java代碼實現向企業微信用戶發送消息


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);
    }

版權聲明:本文為CSDN博主「jay_boolean」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_22798455/article/details/81216589

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM