微信企业号给关注的用户主动发送推送消息

[1].[文件] SendWeChatMessage.java ~ 13KB    下载(2) 跳至 [1]

?
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package com.pansoft.common.weChat;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
 
import javax.net.ssl.HttpsURLConnection;
 
import net.sf.json.JSONObject;
 
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.DefaultHttpParams;
 
import com.pansoft.common.util.Properties;
 
/**
  * @author flyman 2015-8-7
  */
 
public class SendWeChatMessage {
     // 系统properties文件名称
     private static final String EMAILCONFIG = "emailAndMsgConfig" ;
     // 发送消息类型
     private final static String MSGTYPE = "text" ;
 
     // 发送消息分组所有成员
     // private final static String TOPARTY = "@all";
     // 获取配置文件中的值
     private final static String CORPID = Properties.getValue(EMAILCONFIG, "corpid" , "" ); // 需要自己申请,官网有试用企业号
                                                                                         // 可以申请试用
     private final static String CORPSECRET = Properties.getValue(EMAILCONFIG, "corpsecret" , "" );
     // 获取访问权限码URL
     private final static String ACCESS_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken" ;
     // 创建会话请求URL
     private final static String CREATE_SESSION_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" ;
 
     // 获取接口访问权限码
     public String getAccessToken() {
         HttpClient client = new HttpClient();
         PostMethod post = new PostMethod(ACCESS_TOKEN_URL);
         post.releaseConnection();
         post.setRequestHeader( "Content-Type" , "application/x-www-form-urlencoded;charset=UTF-8" );
         NameValuePair[] param = { new NameValuePair( "corpid" , CORPID), new NameValuePair( "corpsecret" , CORPSECRET) };
         // 设置策略,防止报cookie错误
         DefaultHttpParams.getDefaultParams().setParameter( "http.protocol.cookie-policy" , CookiePolicy.BROWSER_COMPATIBILITY);
         // 给post设置参数
         post.setRequestBody(param);
         String result = "" ;
         try {
             client.executeMethod(post);
             result = new String(post.getResponseBodyAsString().getBytes( "gbk" ));
         } catch (IOException e) {
             e.printStackTrace();
         }
         // 将数据转换成json
         JSONObject jasonObject = JSONObject.fromObject(result);
         result = (String) jasonObject.get( "access_token" );
         // System.out.println(result);
 
         post.releaseConnection();
 
         return result;
 
     }
 
     /**
      * 企业接口向下属关注用户发送微信消息(实现方式一)
      *
      * @param touser
      *            成员ID列表(消息接收者,多个接收者用‘|’分隔,最多支持1000个)。特殊情况:指定为@all,
      *            则向关注该企业应用的全部成员发送
      * @param toparty
      *            部门ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数
      * @param totag
      *            标签ID列表,多个接收者用‘|’分隔。当touser为@all时忽略本参数
      * @param content
      *            消息内容
      * @return
      */
     @SuppressWarnings ( "deprecation" )
     public String sendWeChatMessage(String touser, String toparty, String totag, String content) {
         HttpClient client = new HttpClient();
         String ACCESS_TOKEN = getAccessToken();
         StringBuffer sb = new StringBuffer();
         sb.append( "{" );
         sb.append( "\"touser\":" + "\"" + touser + "\"," );
         sb.append( "\"toparty\":" + "\"" + toparty + "\"," );
         sb.append( "\"totag\":" + "\"" + totag + "\"," );
         sb.append( "\"msgtype\":" + "\"" + "text" + "\"," );
         sb.append( "\"agentid\":" + "\"" + "21" + "\"," );
         sb.append( "\"text\":" + "{" );
         sb.append( "\"content\":" + "\"" + content + "\"}," );
         sb.append( "\"debug\":" + "\"" + "1" + "\"" );
         sb.append( "}" );
         // 请求链接
         String url = CREATE_SESSION_URL + ACCESS_TOKEN;
         PostMethod post = new PostMethod(url);
         post.releaseConnection();
         post.setRequestHeader( "Content-Type" , "application/json;charset=UTF-8" );
         // 设置策略,防止报cookie错误
         DefaultHttpParams.getDefaultParams().setParameter( "http.protocol.cookie-policy" , CookiePolicy.BROWSER_COMPATIBILITY);
         // 给post设置参数
         post.setRequestBody(sb.toString());
         String result = "" ;
         try {
             client.executeMethod(post);
             result = new String(post.getResponseBodyAsString().getBytes( "gbk" ));
         } catch (IOException e) {
             e.printStackTrace();
         }
         System.out.println(result);
 
         post.releaseConnection();
 
         return result;
 
     }
 
     /**
      * 此方法可以发送任意类型消息
      *
      * @param msgType
      *            text|image|voice|video|file|news
      * @param touser
      *            成员ID列表(消息接收者,多个接收者用‘|’分隔,最多支持1000个)。特殊情况:指定为@all,
      *            则向关注该企业应用的全部成员发送
      * @param toparty
      *            部门ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数
      * @param totag
      *            标签ID列表,多个接收者用‘|’分隔。当touser为@all时忽略本参数
      * @param content
      *            msgType=text时 ,文本消息内容
      * @param mediaId
      *            msgType=image|voice|video时 ,对应消息信息ID(--------)
      * @param title
      *            msgType=news|video时,消息标题
      * @param description
      *            msgType=news|video时,消息描述
      * @param url
      *            msgType=news时,消息链接
      * @param picurl
      *            msgType=news时,图片路径
      * @param safe
      *            表示是否是保密消息,0表示否,1表示是,默认0
      */
     public void sendWeChatMsg(String msgType, String touser, String toparty, String totag, String content, String mediaId, String title,
             String description, String url, String picurl, String safe) {
 
         URL uRl;
         String ACCESS_TOKEN = getAccessToken();
         // 拼接请求串
         String action = CREATE_SESSION_URL + ACCESS_TOKEN;
         // 封装发送消息请求json
         StringBuffer sb = new StringBuffer();
         sb.append( "{" );
         sb.append( "\"touser\":" + "\"" + touser + "\"," );
         sb.append( "\"toparty\":" + "\"" + toparty + "\"," );
         sb.append( "\"totag\":" + "\"" + totag + "\"," );
         if (msgType.equals( "text" )) {
             sb.append( "\"msgtype\":" + "\"" + msgType + "\"," );
             sb.append( "\"text\":" + "{" );
             sb.append( "\"content\":" + "\"" + content + "\"" );
             sb.append( "}" );
         } else if (msgType.equals( "image" )) {
             sb.append( "\"msgtype\":" + "\"" + msgType + "\"," );
             sb.append( "\"image\":" + "{" );
             sb.append( "\"media_id\":" + "\"" + mediaId + "\"" );
             sb.append( "}" );
         } else if (msgType.equals( "voice" )) {
             sb.append( "\"msgtype\":" + "\"" + msgType + "\"," );
             sb.append( "\"voice\":" + "{" );
             sb.append( "\"media_id\":" + "\"" + mediaId + "\"" );
             sb.append( "}" );
         } else if (msgType.equals( "video" )) {
             sb.append( "\"msgtype\":" + "\"" + msgType + "\"," );
             sb.append( "\"video\":" + "{" );
             sb.append( "\"media_id\":" + "\"" + mediaId + "\"," );
             sb.append( "\"title\":" + "\"" + title + "\"," );
             sb.append( "\"description\":" + "\"" + description + "\"" );
             sb.append( "}" );
         } else if (msgType.equals( "file" )) {
             sb.append( "\"msgtype\":" + "\"" + msgType + "\"," );
             sb.append( "\"file\":" + "{" );
             sb.append( "\"media_id\":" + "\"" + mediaId + "\"" );
             sb.append( "}" );
         } else if (msgType.equals( "news" )) {
             sb.append( "\"msgtype\":" + "\"" + msgType + "\"," );
             sb.append( "\"news\":" + "{" );
             sb.append( "\"articles\":" + "[" );
             sb.append( "{" );
             sb.append( "\"title\":" + "\"" + title + "\"," );
             sb.append( "\"description\":" + "\"" + description + "\"," );
             sb.append( "\"url\":" + "\"" + url + "\"," );
             sb.append( "\"picurl\":" + "\"" + picurl + "\"" );
             sb.append( "}" );
             sb.append( "]" );
             sb.append( "}" );
         }
         sb.append( ",\"safe\":" + "\"" + safe + "\"," );
         sb.append( "\"agentid\":" + "\"" + "21" + "\"," );
         sb.append( "\"debug\":" + "\"" + "1" + "\"" );
         sb.append( "}" );
         String json = sb.toString();
         try {
 
             uRl = new URL(action);
 
             HttpsURLConnection http = (HttpsURLConnection) uRl.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(json.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" );
 
             System.out.println( "请求返回结果:" + result);
 
             os.flush();
 
             os.close();
 
         } catch (Exception e) {
 
             e.printStackTrace();
 
         }
     }
 
     /**
      * 企业接口向下属关注用户发送微信消息(实现方式二)
      *
      * @param touser
      *            成员ID列表(消息接收者,多个接收者用‘|’分隔,最多支持1000个)。特殊情况:指定为@all,
      *            则向关注该企业应用的全部成员发送
      * @param toparty
      *            部门ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数
      * @param totag
      *            标签ID列表,多个接收者用‘|’分隔。当touser为@all时忽略本参数
      * @param content
      *            消息内容
      * @param safe
      *            消息是否保密
      * @return
      */
     public void sendWeChatMsgText(String touser, String toparty, String totag, String content, String safe) {
 
         URL uRl;
         String ACCESS_TOKEN = getAccessToken();
         // 拼接请求串
         String action = CREATE_SESSION_URL + ACCESS_TOKEN;
         // 封装发送消息请求json
         StringBuffer sb = new StringBuffer();
         sb.append( "{" );
         sb.append( "\"touser\":" + "\"" + touser + "\"," );
         sb.append( "\"toparty\":" + "\"" + toparty + "\"," );
         sb.append( "\"totag\":" + "\"" + totag + "\"," );
 
         sb.append( "\"msgtype\":" + "\"" + MSGTYPE + "\"," );
         sb.append( "\"text\":" + "{" );
         sb.append( "\"content\":" + "\"" + content + "\"" );
         sb.append( "}" );
 
         sb.append( ",\"safe\":" + "\"" + safe + "\"," );
         sb.append( "\"agentid\":" + "\"" + "21" + "\"," );
         sb.append( "\"debug\":" + "\"" + "1" + "\"" );
         sb.append( "}" );
         String json = sb.toString();
         try {
 
             uRl = new URL(action);
 
             HttpsURLConnection http = (HttpsURLConnection) uRl.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(json.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" );
 
             System.out.println( "请求返回结果:" + result);
 
             os.flush();
 
             os.close();
 
         } catch (Exception e) {
 
             e.printStackTrace();
 
         }
     }
 
     public static void main(String[] args) {
         SendWeChatMessage weChat = new SendWeChatMessage();
         weChat.sendWeChatMsgText( "mxlydq" , "2" , "" , "信息中心通知" , "0" );
         // weChat.sendWeChatMsg("text", "mxlydx", "4", "", "测试senMsg", "", "",
         // "", "", "", "0");
         // weChat.sendWeChatMessage("mxlydq", "2", "", "Hi");
     }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值