微信群发功能

微信的群发功能个人觉得比较复杂一点
1.如果是纯文字的群发比较简单
2.如果是图片的,需要获取thumb_media_id
3.如果是图文信息,需要获取thumb_media_id

获取thumb_media_id,需要先上传媒体资源到服务器,且必须是永久的,调用的接口如下所示:
这里写图片描述

其中media类型共有5种
图片(image): 2M,支持bmp/png/jpeg/jpg/gif格式
语音(voice):2M,播放长度不超过60s,mp3/wma/wav/amr格式
视频(video):10MB,支持MP4格式
缩略图(thumb):64KB,支持JPG格式
代码演示:

public static void  getMediaId(String appId,String appSecret) {
        String addImage = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN";

        //上传临时素材
        String addImage2 = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=thumb";

        //上传永久素材
        String addImage3 = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=thumb";

        String filepath ="src/main/webapp/image/1.jpg";

        AccessToken at = WeixinUtil.getAccessToken(appId, appSecret);
        String token = at.getToken();
        //临时素材上传
       /* String url = addImage2.replace("ACCESS_TOKEN",token);
        UploadFile.postFile(url,filepath,"Hello World","shshsuhsushsh");*/
        //上传永久素材
        String url2 = addImage3.replace("ACCESS_TOKEN",token);
        UploadFile.postImgFile(url2,filepath);
        File file = new File("src/main/webapp/image/1.jpg");
        System.out.print(file.exists());
    }
public class UploadFile {
public static String postFile(String url, String filePath,
                                  String title,String introduction) {
        File file = new File(filePath);
        if(!file.exists())
            return null;
        String result = null;
        try {
            URL url1 = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Cache-Control", "no-cache");
            String boundary = "-----------------------------"+System.currentTimeMillis();
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);

            OutputStream output = conn.getOutputStream();
            output.write(("--" + boundary + "\r\n").getBytes());
            output.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", file.getName()).getBytes());
            output.write("Content-Type: video/mp4 \r\n\r\n".getBytes());
            byte[] data = new byte[1024];
            int len =0;
            FileInputStream input = new FileInputStream(file);
            while((len=input.read(data))>-1){
                output.write(data, 0, len);
            }
            output.write(("--" + boundary + "\r\n").getBytes());
            output.write("Content-Disposition: form-data; name=\"description\";\r\n\r\n".getBytes());
            output.write(String.format("{\"title\":\"%s\", \"introduction\":\"%s\"}",title,introduction).getBytes());
            output.write(("\r\n--" + boundary + "--\r\n\r\n").getBytes());
            output.flush();
            output.close();
            input.close();
            InputStream resp = conn.getInputStream();
            StringBuffer sb = new StringBuffer();
            while((len= resp.read(data))>-1)
                sb.append(new String(data,0,len,"utf-8"));
            resp.close();
            result = sb.toString();
            System.out.println(result);
        } catch (ClientProtocolException e) {
            logger.error("postFile,不支持http协议",e);
        } catch (IOException e) {
            logger.error("postFile数据传输失败",e);
        }
        logger.info("{}: result={}",url,result);
        return result;
    }

    //上传图片
    public static String postImgFile(String url, String filePath) {
        File file = new File(filePath);
        if (!file.exists())
            return null;
        String result = null;
        try {
            URL url1 = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Cache-Control", "no-cache");
            String boundary = "-----------------------------" + System.currentTimeMillis();
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            OutputStream output = conn.getOutputStream();
            output.write(("--" + boundary + "\r\n").getBytes());
            output.write(
                    String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", file.getName())
                            .getBytes());
            output.write("Content-Type: image/jpeg \r\n\r\n".getBytes());
            byte[] data = new byte[1024];
            int len = 0;
            FileInputStream input = new FileInputStream(file);
            while ((len = input.read(data)) > -1) {
                output.write(data, 0, len);
            }
            output.write(("\r\n--" + boundary + "\r\n\r\n").getBytes());
            output.flush();
            output.close();
            input.close();
            InputStream resp = conn.getInputStream();
            StringBuffer sb = new StringBuffer();
            while ((len = resp.read(data)) > -1)
                sb.append(new String(data, 0, len, "utf-8"));
            resp.close();
            result = sb.toString();
            System.out.println(result);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(result);
        return result;
    }

这样就可以获取到thumb_media_id,接下来就是群发的功能了。

说到群发的话,这里我用测试号测试了只有文本的可以进行群发,其他的都不成功,官网写着根据标签进行群发【订阅号与服务号认证后均可用】,没交钱没办法,只能试试阉割版的咯。

public static String sendGroupMessage(String token){
        String groupUrl = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=ACCESS_TOKEN";//ACCESS_TOKEN是获取到的access_token,根据分组id发群发消息地址
        String groupUrl1 = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=ACCESS_TOKEN";
        String url = groupUrl1.replace("ACCESS_TOKEN",token);
        String openid1data = "{\"touser\":[\"oBLL2wL5GlPE5wo3ihbmU0VxE7qs\",\"oBLL2wGrduSANLkm4BheKclWCcKQ\"],\"msgtype\": \"text\",\"text\": {\"content\": \"测试文本666消息\"}}";
        String group1data = "{\"filter\":{\"is_to_all\":false,\"group_id\":\"3\"},\"text\":{\"content\":\"群发消息测试\"},\"msgtype\":\"text\"}";
        JSONObject json = CommUtil.httpRequest(url, "POST", openid1data);
        return json.toString();
    }


    /** 
     * 发起https请求并获取结果 
     *  
     * @param requestUrl 请求地址 
     * @param requestMethod 请求方式(GET、POST) 
     * @param outputStr 提交的数据 
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) 
     */  
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;  
        StringBuffer buffer = new StringBuffer();  
        try {  
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化  
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());  
            // 从上述SSLContext对象中得到SSLSocketFactory对象  
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);  

            httpUrlConn.setDoOutput(true);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  
            // 设置请求方式(GET/POST)  
            httpUrlConn.setRequestMethod(requestMethod);  

            if ("GET".equalsIgnoreCase(requestMethod))  
                httpUrlConn.connect();  

            // 当有数据需要提交时  
            if (null != outputStr) {  
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式,防止中文乱码  
                outputStream.write(outputStr.getBytes("UTF-8"));  
                outputStream.close();  
            }  

            // 将返回的输入流转换成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            // 释放资源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (ConnectException ce) {
          ce.printStackTrace();
        } catch (Exception e) {  
           e.printStackTrace();
        }  
        return jsonObject;  
    }  

以上代码仅供参考,未在真实环境测过,不知性能如何

参考资料
http://blog.csdn.net/oarsman/article/details/51538078
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738729
http://blog.csdn.net/heboy19/article/details/49815611
http://www.cnblogs.com/h–d/p/5638092.html
http://lib.csdn.net/article/wechat/55774

下载地址
http://download.csdn.net/download/ooiuy450/9957982

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
vb群发消息软件源码,本程序是用vb6在clswindow2.1基础上开的,是对微信客户端进行自动化处理的,完全模拟手工操作,稳定且绝度安全,不会被封。懂代码的可以稍微修改变成定时群发,批量指定目标人群群发。绝对物超所值,代码浅显易懂。 这种非常实用的软件作者选择开源,不像一些同行,摸通了一点技术就藏着掖着,没有共享精神,作者再此完全开源,没有dll没有ocx,clswindow2.1库也是作者精心打造可以用于许多自动化操作方面,非常方便。 各位觉得好麻烦给5分好评。 下面附带一下clswindow2.1更新记录,算是2.1这版本的非正式布吧。 '============================================================================================== '名 称:windows窗体控制类v2.1 '描 述:一个操作windows窗口的类,可对窗口进行很多常用的操作(类名为clsWindow) '使用范例:Dim window As New clsWindow ' window.GetWindowByTitle("计算器").closeWindow '编 程:sysdzw 原创开,如果有需要对模块扩充或更新的话请邮箱我一份,共同维护 '布日期:2013/06/01 '博 客:http://blog.163.com/sysdzw ' http://blog.csdn.net/sysdzw 'Email :sysdzw@163.com 'QQ :171977759 '版 本:V1.0 初版 2012/12/03 ' V1.1 修正了几个正则相关的函数,调整了部分类结构 2013/05/28 ' V1.2 增加属性Caption,可以获取或设置当前标题栏 2013/05/29 ' V1.3 增加了方法Focus,可以激活当前窗口 2013/06/01 ' 增加了方法Left,Top,Width,Height,Move,处理窗口位置等 ' V1.4 增加了窗口位置调整的几个函数 2013/06/04 ' 增加了得到应用程序路径的函数AppName ' 增加了得到应用程序启动参数的函数AppCommandLine ' V1.5 增加了窗口最大最小化,隐藏显示正常的几个函数 2013/06/06 ' 增加了获取控件相关函数是否使用正则的参数UseRegExp默认F ' V1.6 将Left,Top函数改为属性,可获得可设置 2013/06/10 ' V1.7 增加函数:CloseApp 结束进程 2013/06/13 ' 修正了部分跟正则匹配相关的函数 ' 增加函数:GetElementTextByText ' 增加函数:GetElementHwndByText ' V1.8 增加函数:GetWindowByClassName 2013/06/26 ' 增加函数:GetWindowByClassNameEx ' 增加函数:GetWindowByAppName ' 增加私有变量hWnd_ ' 增加属性hWnd,可设置,单设置时候会检查,非法则设置为0 ' 更新GetWindowByTitleEx函数,使之可以选择性支持正则 ' 删除GetWindowByTitleRegExp函数,合并到上面函数 ' 增加SetFocus函数,调用Focus实现,为了是兼容VB习惯

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值