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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
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

  

posted @   红尘沙漏  阅读(1714)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2021-03-25 springcloud 父类pom.xml文件配置
点击右上角即可分享
微信分享提示