课程咨询 :186 8716 1620      qq:2066486918

昆明Java培训 > 达内新闻 > 怎么用httpClient实现微信公众号的消息群发
  • 怎么用httpClient实现微信公众号的消息群发

    发布:昆明Java培训      来源:达内新闻      时间:2016-09-22

  • 昆明Java培训机构的老师今天教你怎么用httpClient实现微信公众号消息群发。

    1、实现功能

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

    2、基本步骤

    前提:

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

    发送消息步骤:

    发送一个请求微信去获取access_token

    发送一个请求去请求微信发送消息

    3、实践

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

    1)maven依赖

    <dependency>

    <groupId>org.apache.httpcomponents</groupId>

    <artifactId>httpclient</artifactId>

    <version>4.3.1</version>

    </dependency>

    2)httpClient使用方法

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

    创建HttpClient对象。

    创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

    如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。

    调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

    调用HttpResponse的getAllHeaders()、getHeaders(String ame)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

    释放连接。无论执行方法是否成功,都必须释放连接——这里使用了连接池,可以交给连接池去处理

    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);

    }

    学Java开发就到昆明达内Java培训班!了解详情请登陆昆明达内Java培训官网(km.Java.tedu.cn)!

    推荐文章

上一篇:昆明达内java培训:java线程公平锁

下一篇:Java中的Bigdecimal类型运算

最新开班日期  |  更多

Java--零基础全日制班

Java--零基础全日制班

开班日期:12/29

Java--零基础业余班

Java--零基础业余班

开班日期:12/29

Java--周末提升班

Java--周末提升班

开班日期:12/29

Java--零基础周末班

Java--零基础周末班

开班日期:12/29

  • 网址:http://km .java.tedu.cn      地址:昆明市官渡区春城路62号证券大厦附楼6楼
  • 课程培训电话:186 8716 1620      qq:2066486918    全国服务监督电话:400-827-0010
  • 服务邮箱 ts@tedu.cn
  • 2001-2016 达内国际公司(TARENA INTERNATIONAL,INC.) 版权所有 京ICP证08000853号-56