java微信接口之五—消息分组群发

2019-03-02 01:08|来源: 网路

一、微信消息分组群发接口简介

  1、请求:该请求是使用post提交地址为: 

  https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=ACCESS_TOKEN

    其中ACCESS_TOKEN是我们动态获取的

    发送的数据:(这里使用图文消息示例)

{
   "filter":{
      "group_id":"2"
   },
   "mpnews":{
      "media_id":"123dsdajkasd231jhksad"
   },
    "msgtype":"mpnews"
}

  filter,用于设定图文消息的接收者;
  group_id,群发到的分组的group_id(可在java微信接口之二—获取用户组);

  mpnews,用于设定即将发送的图文消息;

  media_id, 用于群发的消息的media_id(可在java微信接口之四—上传素材中获取);  msgtype,群发的消息类型,图文消息为mpnews,文本消息为text,语音为voice,音乐为music,图片为image,视频为video.

 2、响应:该响应也是以json方式返回的

  正确的时候返回的数据: 

{
   "errcode":0,
   "errmsg":"send job submission success",
   "msg_id":34182
}

  errcode 错误码
  errmsg 错误信息
  msg_id 消息ID 

  错误的时候返回的数据:{"errcode":40004,"errmsg":"invalid media type"}

  errcode,为错误代码,errmsg为错误信息

  具体api可查看:http://mp.weixin.qq.com/wiki/index.php?title=%E9%AB%98%E7%BA%A7%E7%BE%A4%E5%8F%91%E6%8E%A5%E5%8F%A3

二、关于java代码的调用

  该接口的调用与java微信接口四—上传素材一样,需要使用到commons-httpclient。其中数据是构造成json数据后,放在post方法请求体里面发送给服务器端。

三、代码实现

 

  1 package com.demo.test;
  2 
  3 import java.io.File;
  4 import java.util.ArrayList;
  5 import java.util.HashMap;
  6 import java.util.List;
  7 import java.util.Map;
  8 
  9 import org.apache.commons.httpclient.methods.PostMethod;
 10 import org.apache.commons.httpclient.methods.multipart.FilePart;
 11 import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
 12 import org.apache.commons.httpclient.methods.multipart.Part;
 13 import org.apache.http.HttpEntity;
 14 import org.apache.http.HttpResponse;
 15 import org.apache.http.HttpStatus;
 16 import org.apache.http.client.HttpClient;
 17 import org.apache.http.client.methods.HttpGet;
 18 import org.apache.http.impl.client.DefaultHttpClient;
 19 import org.apache.http.util.EntityUtils;
 20 
 21 import com.google.gson.Gson;
 22 import com.google.gson.JsonArray;
 23 import com.google.gson.JsonObject;
 24 import com.google.gson.JsonParser;
 25 
 26 public class Test
 27 {
 28     public static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";// 获取access
 29     public static final String UPLOAD_IMAGE_URL = "http://file.api.weixin.qq.com/cgi-bin/media/upload";// 上传多媒体文件
 30     public static final String UPLOAD_FODDER_URL = "https://api.weixin.qq.com/cgi-bin/media/uploadnews";
 31     public static final String GET_USER_GROUP = "https://api.weixin.qq.com/cgi-bin/groups/get"; // url
 32     public static final String SEND_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall";
 33     public static final String APP_ID = "wxa549b28c24cf341e";
 34     public static final String SECRET = "78d8a8cd7a4fa700142d06b96bf44a37";
 35 
 36 
 37     /**
 38      * 发送消息
 39      * 
 40      * @param uploadurl
 41      *            apiurl
 42      * @param access_token
 43      * @param data
 44      *            发送数据
 45      * @return
 46      */
 47     public static String sendMsg(String url, String token, String data)
 48     {
 49         org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
 50         String sendurl = String.format("%s?access_token=%s", url, token);
 51         PostMethod post = new UTF8PostMethod(sendurl);
 52         post
 53                 .setRequestHeader(
 54                         "User-Agent",
 55                         "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:30.0) Gecko/20100101 Firefox/30.0");
 56 
 57         post.setRequestHeader("Host", "file.api.weixin.qq.com");
 58         post.setRequestHeader("Connection", "Keep-Alive");
 59         post.setRequestHeader("Cache-Control", "no-cache");
 60         String result = null;
 61         try
 62         {
 63             post.setRequestBody(data);
 64             int status = client.executeMethod(post);
 65             if (status == HttpStatus.SC_OK)
 66             {
 67                 String responseContent = post.getResponseBodyAsString();
 68                 System.out.println(responseContent);
 69                 JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象
 70                 JsonObject json = jsonparer.parse(responseContent)
 71                         .getAsJsonObject();
 72                 if (json.get("errcode") != null
 73                         && json.get("errcode").getAsString().equals("0"))
 74                 {
 75                     result = json.get("errmsg").getAsString();
 76                 }
 77             }
 78         }
 79         catch (Exception e)
 80         {
 81             e.printStackTrace();
 82         }
 83         finally
 84         {
 85             return result;
 86         }
 87     }
 88     
 89     public static class UTF8PostMethod extends PostMethod {//防止发送的消息产生乱码
 90         public UTF8PostMethod(String url) {
 91             super(url);
 92         }
 93 
 94         @Override
 95         public String getRequestCharSet() {//文本编码格式
 96             return "UTF-8";
 97         }
 98     }
 99 
100     public static void main(String[] args) throws Exception
101     {
102         String accessToken = getToken(GET_TOKEN_URL, APP_ID, SECRET);// 获取token在微信接口之一中获取
103         if (accessToken != null)// token成功获取
104         {
105             System.out.println(accessToken);
106             File file = new File("f:" + File.separator + "2000.JPG"); // 获取本地文件
107             String id = uploadImage(UPLOAD_IMAGE_URL, accessToken, "image",
108                     file);// java微信接口之三—上传多媒体文件 可获取
109             if (id != null)
110             {
111                 // 构造数据
112                 Map map = new HashMap();
113                 map.put("thumb_media_id", id);
114                 map.put("author", "wxx");
115                 map.put("title", "标题");
116                 map.put("content", "测试fdsfdsfsdfssfdsfsdfsdfs");
117                 map.put("digest", "digest");
118                 map.put("show_cover_pic", "0");
119 
120                 Map map2 = new HashMap();
121                 map2.put("thumb_media_id", id);
122                 map2.put("author", "wxx");
123                 map2.put("content_source_url", "www.google.com");
124                 map2.put("title", "标题");
125                 map2.put("content", "测试fdsfdsfsdfssfdsfsdfsdfs");
126                 map2.put("digest", "digest");
127 
128                 Map map3 = new HashMap();
129                 List<Map> list = new ArrayList<Map>();
130                 list.add(map);
131                 list.add(map2);
132                 map3.put("articles", list);
133 
134                 Gson gson = new Gson();
135                 String result = gson.toJson(map3);// 转换成json数据格式
136                 String mediaId = uploadFodder(UPLOAD_FODDER_URL, accessToken,
137                         result);
138                 if (mediaId != null)
139                 {
140                     String ids = getGroups(GET_USER_GROUP, accessToken);// 在java微信接口之二—获取用户组
141                     if (ids != null)
142                     {
143                         String[] idarray = ids.split(",");// 用户组id数组
144                         for (String gid : idarray)
145                         {
146                             
147                             JsonObject jObj = new JsonObject();
148                             JsonObject filter = new JsonObject();
149                             filter.addProperty("group_id", gid);
150                             jObj.add("filter", filter);
151  
152  
153                             JsonObject mpnews = new JsonObject();
154                             mpnews.addProperty("media_id", mediaId);
155                             jObj.add("mpnews", mpnews);
156  
157                             jObj.addProperty("msgtype", "mpnews"); 
158                             System.out.println(jObj.toString());
159 
160                             String result2 = sendMsg(SEND_MESSAGE_URL,
161                                     accessToken, jObj.toString());
162                             System.out.println(result2);
163                         }
164                     }
165                 }
166 
167             }
168         }
169     }
170 }

  发成功后会打印消息,但由于微信服务器的原因,消息不会立即发送,会过一段时间发送。


转自:http://www.cnblogs.com/always-online/p/3871961

相关问答

更多
  • 1. 调用微信的发送消息接口 2. 如果有交互,调用微信的js-sdk 3. 参考微信文档:http://mp.weixin.qq.com/wiki/home/
  • 其实,就是写特定格式的 web 应用 TX 官网拿接口说明,然后搭建
  • 能使用的!微信 在安卓手机里可以使用,安装是用java 开发的,所以 可以用java开发
  • 我刚做了一个调用接口生成一个二维码 在自己网站内展示,通过微信扫描 二维码支付。
  • 导入httpcore的jar包,httpclient用httppost调用 https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=ACCESS_TOKEN 这个接口 分别传入用户的openid即可 参考微信的wiki http://mp.weixin.qq.com/wiki/15/5380a4e6f02f2ffdc7981a8ed7a40753.html 根据OpenID列表群发【订阅号不可用,服务号认证后可用】 接口调用请求说明 ...
  • 在公众平台网站上,为订阅号提供了每天一条的群发权限,为服务号提供每月(自然月)4条的群发权限。而对于某些具备开发能力的公众号运营者,可以通过高级群发接口,实现更灵活的群发能力。 请注意: 1、对于认证订阅号,群发接口每天可成功调用1次,此次群发可选择发送给全部用户或某个分组; 2、对于认证服务号虽然开发者使用高级群发接口的每日调用限制为100次,但是用户每月只能接收4条,无论在公众平台网站上,还是使用接口群发,用户每月只能接收4条群发消息,多于4条的群发将对该用户发送失败; 3、具备微信支付权限的公众号,在 ...
  • 使用wechat-card module可以按照以下操作: var card = { card_type: "DISCOUNT", base_info: { // ... }, special_info: { // ... } }; wxCard.card.createCard(card, function(err, cardId) { // 创建成功后,返回卡券的ID });
  • 开启开发模式时不影响群发功能的。现在只有订阅号和服务号群发功能有区别,订阅号每天都可以群发一群消息,服务号一个月才能群发一条消息。你说的那种情况是没有的。
  • 除了推送外,公众号无法主动向用户发送消息。
  • 不会,停用后就不发消息, 如果楼主只是不想让软件发送消息,可以开启消息免打扰模式。 进入微信界面,在微信选项中找到微信运动进入 点击右上的设置进入,向上划动屏幕,开启消息免打扰就可以(如果要关闭微信运动,点击当前界面的停用就可以将微信运动关闭掉)。