httpclient实现微信公众号消息群发

author author     2022-08-05     222

关键词:

1、实现功能 

  向关注了微信公众号的微信用户群发消息。(可以是所有的用户,也可以是提供了微信openid的微信用户集合)

2、基本步骤

前提:

  已经有认证的公众号或者测试公众账号

发送消息步骤:

  1. 发送一个请求微信去获取access_token
  2. 发送一个请求去请求微信发送消息

相关微信接口的信息可以查看:http://www.cnblogs.com/0201zcr/p/5866296.html 有测试账号的申请 + 获取access_token和发送微信消息的url和相关的参数需求。各个参数的意义等。

3、实践

  这里通过HttpClient发送请求去微信相关的接口。

1)maven依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.3.1</version>
</dependency>

2)httpClient使用方法

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

  1. 创建HttpClient对象。
  2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
  3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
  4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
  5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
  6. 释放连接。无论执行方法是否成功,都必须释放连接——这里使用了连接池,可以交给连接池去处理

 3)实例

1、发送请求的类

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.seewo.core.util.json.JsonUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.CertificateException;
import javax.security.cert.X509Certificate;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by zhengcanrui on 16/9/20.
 */
public class WechatAPIHander {

        /**
         * 获取token接口
         */
        private String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
        /**
         * 拉微信用户信息接口
         */
        private String getUserInfoUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}";
        /**
         * 主动推送信息接口(群发)
         */
        private String sendMsgUrl = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token={0}";



        private HttpClient webClient;
        private Log log = LogFactory.getLog(getClass());
        public void initWebClient(String proxyHost, int proxyPort){
            this.initWebClient();
            if(webClient != null && !StringUtils.isEmpty(proxyHost)){
                HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                webClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            }
        }
        /**
         * @desc 初始化创建 WebClient
         */
        public void initWebClient() {
            log.info("initWebClient start....");
            try {
                PoolingClientConnectionManager tcm = new PoolingClientConnectionManager();
                tcm.setMaxTotal(10);
                SSLContext ctx = SSLContext.getInstance("TLS");
                X509TrustManager tm = new X509TrustManager() {

                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {

                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {

                    }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return new java.security.cert.X509Certificate[0];
                    }
                };
                ctx.init(null, new X509TrustManager[] { tm }, null);
                SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                Scheme sch = new Scheme("https", 443, ssf);
                tcm.getSchemeRegistry().register(sch);
                webClient = new DefaultHttpClient(tcm);
            } catch (Exception ex) {
                log.error("initWebClient exception", ex);
            } finally {
                log.info("initWebClient end....");
            }
        }
        /**
         * @desc 获取授权token
         * @param appid
         * @param secret
         * @return
         */
        public String getAccessToken(String appid, String secret) {
            String accessToken = null;
            try {
                log.info("getAccessToken start.{appid=" + appid + ",secret:" + secret + "}");
                String url = MessageFormat.format(this.getTokenUrl, appid, secret);
                String response = executeHttpGet(url);
                Map map = JsonUtils.jsonToMap(response);
                accessToken = (String) map.get("access_token");
               /* Object Object = JSONUtils.parse(response);

                accessToken = jsonObject.getString("access_token");*/
//                accessToken = JsonUtils.read(response, "access_token");
            } catch (Exception e) {
                log.error("get access toekn exception", e);
            }
            return accessToken;
        }
        /**
         * @desc 推送信息
         * @param token
         * @param msg
         * @return
         */
        public String sendMessage(String token,String msg){
            try{
                log.info("\n\nsendMessage start.token:"+token+",msg:"+msg);
                String url = MessageFormat.format(this.sendMsgUrl, token);
                HttpPost post = new HttpPost(url);
                ResponseHandler<?> responseHandler = new BasicResponseHandler();

                //这里必须是一个合法的json格式数据,每个字段的意义可以查看上面连接的说明,content后面的test是要发送给用户的数据,这里是群发给所有人
                msg = "{\"filter\":{\"is_to_all\":true},\"text\":{\"content\":\"test\"},\"msgtype\":\"text\"}\"";

                //设置发送消息的参数
                StringEntity entity = new StringEntity(msg);

                //解决中文乱码的问题
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                post.setEntity(entity);

                //发送请求
                String response = (String) this.webClient.execute(post, responseHandler);
                log.info("return response=====start======");
                log.info(response);
                log.info("return response=====end======");
                return response;

            }catch (Exception e) {
                log.error("get user info exception", e);
                return null;
            }
        }

        /**
         * @desc 发起HTTP GET请求返回数据
         * @param url
         * @return
         * @throws IOException
         * @throws ClientProtocolException
         */
        private String executeHttpGet(String url) throws IOException, ClientProtocolException {
            ResponseHandler<?> responseHandler = new BasicResponseHandler();
            String response = (String) this.webClient.execute(new HttpGet(url), responseHandler);
            log.info("return response=====start======");
            log.info(response);
            log.info("return response=====end======");
            return response;
        }

}

 2、Controller和Service层调用

  @RequestMapping(value = "/testHttpClient", method = RequestMethod.GET)
    public DataMap test() {
        WechatAPIHander wechatAPIHander = new WechatAPIHander();

        //获取access_token
      //第一个参数是你appid,第二个参数是你的秘钥,需要根据你的具体情况换 String accessToken = wechatAPIHander.getAccessToken("appid","scerpt"); //发送消息 wechatAPIHander.sendMessage(accessToken, "测试数据"); return new DataMap().addAttribute("DATA",accessToken); }

 3、结果

  假如你关注了微信公众号中看到你刚刚发送的test消息。

HttpClient学习文档:https://pan.baidu.com/s/1miO1eOg

 致谢:感谢您的阅读

怎样增加公众号群发次数?

...该帐号与QQ账号互通,通过公众号,商家可在微信平台上实现和特定群体的文字、图片、语音、视频的全方位沟通、互动。形成了一种主流的线上线下微信互动营销方式。微信公众号分为服务号和订阅号。服务号每个月可以发四... 查看详情

微信模板消息群发系统

 一、使用场景:微信公众号模板消息群发,用于提醒、通知、营销等。只要关注的用户都可以收到二、使用条件:1、认证服务号2、已经申请开通模板消息功能(认证服务号即可申请)三、功能介绍:微信公众号模板消息一... 查看详情

微信公众号无限群发怎么做

...对服务号的限制是更大的。通过销大师的群发功能,可以实现每天的多次内容群发。高级群发:突破公众号群发次数限制,根据不同条件群发不同人群,个性化营销,可以为已认证服务号提供每日100次的群发能力,即每日群发给... 查看详情

微信公众平台模拟登录自动群发图文消息工具包

无需微信认证即可实现微信公众号自动群发图文消息。使用npmiwechat-mp-hack--saveconstWechat=require(‘wechat-mp-hack‘);constAPI=newWechat(‘公众号账号‘,‘公众号密码‘); 1.1.0版本后不再需要把调用方法包裹在login回调后执行,调用下列... 查看详情

.net微信公众号开发——群发消息

  本文将介绍微信公众号开发中用于群发消息的类MassMessage,包括:(1)MassMessage类;(2)群发;(3)删除;(4)预览;(5)查询发送状态;(6)接收推送群发结果事件。  源代码地址:http://git.oschina.net/xrwang2/x... 查看详情

微信推送信息功能

...信息删除据最新功能里面可以对已经推送的图文消息内容实现删除操作,在“已发送”中找到当前信息删除。如果是纯文字的话不具备此功能。推送人数的上限微信公众号对推送消息的人数没有做限制,当然这里也只能推送订阅... 查看详情

主动发送微信公众平台“模板消息”需要啥条件?

目前有个主动推送日发电量的需求,准备用模版消息实现,但是貌似不满足消息主动下发的条件。①模板消息不能主动下发给没有接受过服务的接收者(故障报警、灾害报警和不涉及营销推广的通知除外)例:某用户仅仅是关注... 查看详情

asp实现微信客服消息群发,asp代码写的

最近一个客户的需求找到我,他想利用公众号给他的粉丝群发客服消息,想发带图文的客服消息,或是带链接的消息,花几分钟研究了一下,比较简单,上代码:微信客服消息发送asp代码如下:<%url="https://api.weixin.qq.com/cgi-bin/m... 查看详情

微信公众号都有哪些功能?

参考技术A问题一:微信公众平台有哪些功能微信公众平台是腾讯公司在微信的基础上新增的功能模块,通过这一平台,个人和企业都可以打造一个微信的公众号,可以群发文字、图片、语音、视频、图文消息五个类别的内容。... 查看详情

高级接口--高级群发接口(代码片段)

...送编辑好的消息给指定用户校验效果;4、群发过程中,微信后台会自动进行图文消息原创校验,请提前设置好相关参数(send_ignore等);5、开发者可以主动设置clientmsgid来避免重复推送。6、群发接口每分钟限制请求60次,超过限制... 查看详情

微信订阅号都有哪些功能?

参考技术A问题一:微信订阅号有什么特点和功能微信公众平台订阅号。主要是提供信息和资讯。一般媒体用的比较多。5.0版本的微信公众平台订阅号主要功能和权限:1.微信公众平台订阅号每天都可以群发一条群发信息。群发的... 查看详情

微信公众平台开发——群发信息

1、目的  完成在微信公众号中群发消息。这里只是完成简单的文字发送。也可以发送语音图片等,只是发送数据格式不同而已,下面有链接,可以查询数据类型的数据发送格式。2、群发短信的流程获取测试公众账号(有账号... 查看详情

群发技术-使用python3给微信好友群发消息

...所有所有群发,则需要自己手动发送多次,或者借助程序实现了。本文即是程序实现教程 一、原理在微信的官方网站上https://weixin.qq.com/,提供了一个网页版的微信,地址为https://wx.qq.com/登录该网页版微信后,可以在网页上... 查看详情

公众号文章如何不群发就可以生成永久链接!

...链接的图文在公众号后台保存好所需图文后用你的手机在微信公众号里发送任意信息(编辑任意信息点击发送)STEP3:进入电脑的公众号后台进入公众号后台左侧的“消息管理”点击发送消息的你的微信号头像(注意一定是点击... 查看详情

c端用户触达方式

...台有不同的解决方案,常见的C端用户触达方式。一、微信公众号1.模板消息公众号模板消息,向认证后的服务号开放。所有服务号都可以在功能->添加功能插件处看到申请模板消息功能的入口,但只有认证后的服务... 查看详情

如何测试微信公众号?

...序,而我们要测试的内容就是这些接口、小程序、H5实现的功能 查看详情

如何测试微信公众号?

...序,而我们要测试的内容就是这些接口、小程序、H5实现的功能 查看详情

验证接入(代码片段)

...条消息;3、企业微信(企业号)为企业,政府,事业单位,实现生产管理和协作运营的移动化,主要用于公司内部通讯使用,旨在为用户提供移动办公,需要先有成员的通讯信息验证才可以关注成功企业微信;还有一个比较明显的... 查看详情