微信公众号开发--群发推送图文消息

群发推送消息,分为三步,先上传图片获得图片的id,再上传图文素材获得Id,最后把素材Id群发给目标

一 上传图片

 1  /**
 2      * 上传图片
 3      *
 4      * @param file  表单名称media
 5      * @param token access_token  type = "image";
 6      * @param type  type只支持四种类型素材(video/image/voice/thumb)
 7      */
 8     @RequestMapping("uoloadimage.action")
 9     public String uploadMedia( ) {
10        /* if (file == null || token == null || type == null) {
11             return null;
12         }
13 
14         if (!file.exists()) {
15             System.out.println("上传文件不存在,请检查!");
16             return null;
17         }*/
18         String token=WxaApi.accessToken.getAccessToken();
19         String type="image";
20         File file=new File("D:/1.JPG");
21         /*
22          * 
23          */
24         String url = "https://api.weixin.qq.com/cgi-bin/media/upload";
25         com.alibaba.fastjson.JSONObject jsonObject = null;
26         PostMethod post = new PostMethod(url);
27         post.setRequestHeader("Connection", "Keep-Alive");
28         post.setRequestHeader("Cache-Control", "no-cache");
29         FilePart media;
30         HttpClient httpClient = new HttpClient();
31         //信任任何类型的证书
32         Protocol myhttps = new Protocol("https", new SSLProtocolSocketFactory(), 443);
33         Protocol.registerProtocol("https", myhttps);
34 
35         try {
36             media = new FilePart("media", file);
37             Part[] parts = new Part[]{new StringPart("access_token", token),
38                     new StringPart("type", type), media};
39             MultipartRequestEntity entity = new MultipartRequestEntity(parts,
40                     post.getParams());
41             post.setRequestEntity(entity);
42             int status = httpClient.executeMethod(post);
43             if (status == HttpStatus.SC_OK) {
44                 String text = post.getResponseBodyAsString();
45                 jsonObject = com.alibaba.fastjson.JSONObject.parseObject(text);
46             } else {
47                 System.out.println("upload Media failure status is:" + status);
48             }
49         } catch (FileNotFoundException e) {
50             e.printStackTrace();
51         } catch (HttpException e) {
52             e.printStackTrace();
53         } catch (IOException e) {
54             e.printStackTrace();
55         }
56         String media_id = jsonObject.get("media_id").toString();
57         System.out.println("media_id="+media_id);
58         return null;
59     }
media_id 为下一步需要的图片Id

二 上传素材
 1 /**
 2      * 上传图文消息素材
 3      */
 4     @RequestMapping("uploadnews.action")
 5     public void uploadnews(){
 6         /*Articles    是    图文消息,一个图文消息支持1到8条图文
 7          *thumb_media_id    是    图文消息缩略图的media_id,可以在基础支持-上传多媒体文件接口中获得
 8          *author    否    图文消息的作者
 9          *title    是    图文消息的标题
10          *content_source_url    否    在图文消息页面点击“阅读原文”后的页面,受安全限制,如需跳转Appstore,可以使用itun.es或appsto.re的短链服务,并在短链后增加 #wechat_redirect 后缀。
11          *content    是    图文消息页面的内容,支持HTML标签。具备微信支付权限的公众号,可以使用a标签,其他公众号不能使用,如需插入小程序卡片,可参考下文。
12          *digest    否    图文消息的描述,如本字段为空,则默认抓取正文前64个字
13          *show_cover_pic    否    是否显示封面,1为显示,0为不显示
14          *need_open_comment    否    Uint32 是否打开评论,0不打开,1打开
15          *only_fans_can_comment    否    Uint32 是否粉丝才可评论,0所有人可评论,1粉丝才可评论*/
16          JSONObject js1=new JSONObject();
17          js1.put("thumb_media_id", "y06hl0sGMuo9UEOFSk-*******-R7-BCYRZzuk1vuJ7zsmfZdm2nmpExnt7wddB");
18          js1.put("author", "wu");
19          js1.put("title", "推送1");js1.put("content_source_url", "");js1.put("content", "这是测试公众号推送1");
20          js1.put("digest", "");js1.put("show_cover_pic", "1");js1.put("need_open_comment", "1");
21          js1.put("only_fans_can_comment", "0");
22          
23          JSONObject js2=new JSONObject();
24          js2.put("thumb_media_id", "hxlqiCyuyv4_paYLZjKQ7*************w9XHaxjLL87QqcvLf74dG60kdEDRv");
25          js2.put("author", "chao");
26          js2.put("title", "推送2");js2.put("content_source_url", "");js2.put("content", "这是测试公众号推送2");js2.put("digest", "");
27          js2.put("show_cover_pic", "1");js2.put("need_open_comment", "1");
28          js2.put("only_fans_can_comment", "0");
29          
30          JSONArray jsarray=new JSONArray();
31          jsarray.add(js1.toString());jsarray.add(js2.toString());
32          
33          JSONObject js=new JSONObject();
34          js.put("articles", jsarray.toString());
35          
36          String jsstring = js.toString();
37          System.out.println(jsstring);
38          String url="https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=ACCESS_TOKEN".replaceAll("ACCESS_TOKEN", WxaApi.accessToken.getAccessToken());
39          String httpsResponse = netWorkHelper.getHttpsResponse(url, "POST", jsstring);
40          System.out.println(httpsResponse);
41          JSONObject newsjs=JSONObject.fromObject(httpsResponse);
42          String newsmedia = newsjs.getString("media_id");
43          
44     }

json字符串的格式可以参考开发文档,本Demo是发送两条数据

 

三 群发

/**
     * 上传的图文素材群发
     */
    @RequestMapping("sendall.get")
    public void sendall(){
        /*
         *     filter    是    用于设定图文消息的接收者
                is_to_all    否    用于设定是否向全部用户发送,值为true或false,选择true该消息群发给所有用户,选择false可根据tag_id发送给指定群组的用户
            mpnews    是    用于设定即将发送的图文消息
                media_id    是    用于群发的消息的media_id
            msgtype    是    群发的消息类型,图文消息为mpnews,文本消息为text,语音为voice,音乐为music,图片为image,视频为video,卡券为wxcard
            send_ignore_reprint    是    图文消息被判定为转载时,是否继续群发。 1为继续群发(转载),0为停止群发。 该参数默认为0。
         */
        JSONObject j1=new JSONObject();
        JSONObject j11=new JSONObject();
        JSONObject j21=new JSONObject();
        j11.put("is_to_all", true);
        j21.put("media_id", "BiawhA7misCxWfAiuXUSi******************UYVf-baKrSsmTouuxCzIcR_k43Hg2oeFo");
        j1.put("filter",j11.toString());
        j1.put("mpnews", j21.toString());
        j1.put("msgtype", "mpnews");
        j1.put("send_ignore_reprint", 1);
        System.out.println(j1.toString());
        
        String url="https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN", WxaApi.accessToken.getAccessToken());
        String httpsResponse = netWorkHelper.getHttpsResponse(url, "POST", j1.toString());
        System.out.println(httpsResponse);
    }

只有实名认证过的才能发送成功,遇到错误直接百度,流程是没问题的,错误可能是自己的参数或者自己公众号的问题,测试公众号没法用,可以把第三步换成预览的方法,预览方法如下

 1 /**
 2      * 推送预览
 3      */
 4     @RequestMapping("preview.action")
 5     public void preview (){
 6         JSONObject j1=new JSONObject();
 7         j1.put("media_id", "这为第二步返回的iD    ::iuXUSiShxnw6xeJSUYVf-baKrSsmTouuxCzIcR_k43Hg2oeFo");
 8         JSONObject j=new JSONObject();
 9         j.put("touser", "这是发送目标的微信openid");
10         j.put("mpnews", j1.toString());
11         j.put("msgtype", "mpnews");
12         String url="https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN", WxaApi.accessToken.getAccessToken());
13         String httpsResponse = netWorkHelper.getHttpsResponse(url, "POST", j.toString());
14         System.out.println(httpsResponse);
15     }
netWorkHelper工具类 可以翻我其他的随笔有代码

转载于:https://www.cnblogs.com/chaoswu/p/10189226.html

你可能感兴趣的:(json)