Java教程

Java代码实现向企业微信用户发送消息

本文主要是介绍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

  

这篇关于Java代码实现向企业微信用户发送消息的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!