httpClient实现微信公众号消息群发
本文内容纲要:
1、实现功能
向关注了微信公众号的微信用户群发消息。(可以是所有的用户,也可以是提供了微信openid的微信用户集合)
2、基本步骤
前提:
****已经有认证的公众号或者测试公众账号
发送消息步骤:
- 发送一个请求微信去获取access_token
- 发送一个请求去请求微信发送消息
相关微信接口的信息可以查看: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发送请求、接收响应很简单,一般需要如下几步即可。
- 创建HttpClient对象。
- 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
- 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParamsparams)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntityentity)方法来设置请求参数。
- 调用HttpClient对象的execute(HttpUriRequestrequest)发送请求,该方法返回一个HttpResponse。
- 调用HttpResponse的getAllHeaders()、getHeaders(Stringname)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
- 释放连接。无论执行方法是否成功,都必须释放连接——这里使用了连接池,可以交给连接池去处理
3)实例
1、发送请求的类
importcom.alibaba.druid.support.json.JSONUtils;
importcom.alibaba.druid.support.logging.Log;
importcom.alibaba.druid.support.logging.LogFactory;
importcom.alibaba.fastjson.JSON;
importcom.alibaba.fastjson.JSONObject;
importcom.seewo.core.util.json.JsonUtils;
importorg.apache.commons.collections.map.HashedMap;
importorg.apache.commons.lang.StringUtils;
importorg.apache.http.HttpHost;
importorg.apache.http.NameValuePair;
importorg.apache.http.client.ClientProtocolException;
importorg.apache.http.client.HttpClient;
importorg.apache.http.client.ResponseHandler;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.conn.params.ConnRoutePNames;
importorg.apache.http.conn.scheme.Scheme;
importorg.apache.http.conn.ssl.SSLSocketFactory;
importorg.apache.http.entity.StringEntity;
importorg.apache.http.impl.client.BasicResponseHandler;
importorg.apache.http.impl.client.DefaultHttpClient;
importorg.apache.http.impl.conn.PoolingClientConnectionManager;
importorg.apache.http.message.BasicNameValuePair;
importorg.springframework.http.HttpHeaders;
importorg.springframework.http.MediaType;
importjavax.net.ssl.SSLContext;
importjavax.net.ssl.X509TrustManager;
importjavax.security.cert.CertificateException;
importjavax.security.cert.X509Certificate;
importjava.io.IOException;
importjava.text.MessageFormat;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.Map;
/**
*Createdbyzhengcanruion16/9/20.
*/
publicclassWechatAPIHander{
/**
*获取token接口
*/
privateStringgetTokenUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
/**
*拉微信用户信息接口
*/
privateStringgetUserInfoUrl="https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}";
/**
*主动推送信息接口(群发)
*/
privateStringsendMsgUrl="https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token={0}";
privateHttpClientwebClient;
privateLoglog=LogFactory.getLog(getClass());
publicvoidinitWebClient(StringproxyHost,intproxyPort){
this.initWebClient();
if(webClient!=null&&!StringUtils.isEmpty(proxyHost)){
HttpHostproxy=newHttpHost(proxyHost,proxyPort);
webClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
}
}
/**
*@desc初始化创建WebClient
*/
publicvoidinitWebClient(){
log.info("initWebClientstart....");
try{
PoolingClientConnectionManagertcm=newPoolingClientConnectionManager();
tcm.setMaxTotal(10);
SSLContextctx=SSLContext.getInstance("TLS");
X509TrustManagertm=newX509TrustManager(){
@Override
publicvoidcheckClientTrusted(java.security.cert.X509Certificate[]x509Certificates,Strings)throwsjava.security.cert.CertificateException{
}
@Override
publicvoidcheckServerTrusted(java.security.cert.X509Certificate[]x509Certificates,Strings)throwsjava.security.cert.CertificateException{
}
@Override
publicjava.security.cert.X509Certificate[]getAcceptedIssuers(){
returnnewjava.security.cert.X509Certificate[0];
}
};
ctx.init(null,newX509TrustManager[]{tm},null);
SSLSocketFactoryssf=newSSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Schemesch=newScheme("https",443,ssf);
tcm.getSchemeRegistry().register(sch);
webClient=newDefaultHttpClient(tcm);
}catch(Exceptionex){
log.error("initWebClientexception",ex);
}finally{
log.info("initWebClientend....");
}
}
/**
*@desc获取授权token
*@paramappid
*@paramsecret
*@return
*/
publicStringgetAccessToken(Stringappid,Stringsecret){
StringaccessToken=null;
try{
log.info("getAccessTokenstart.{appid="+appid+",secret:"+secret+"}");
Stringurl=MessageFormat.format(this.getTokenUrl,appid,secret);
Stringresponse=executeHttpGet(url);
Mapmap=JsonUtils.jsonToMap(response);
accessToken=(String)map.get("access_token");
/*ObjectObject=JSONUtils.parse(response);
accessToken=jsonObject.getString("access_token");*/
//accessToken=JsonUtils.read(response,"access_token");
}catch(Exceptione){
log.error("getaccesstoeknexception",e);
}
returnaccessToken;
}
/**
*@desc推送信息
*@paramtoken
*@parammsg
*@return
*/
publicStringsendMessage(Stringtoken,Stringmsg){
try{
log.info("\n\nsendMessagestart.token:"+token+",msg:"+msg);
Stringurl=MessageFormat.format(this.sendMsgUrl,token);
HttpPostpost=newHttpPost(url);
ResponseHandler<?>responseHandler=newBasicResponseHandler();
//这里必须是一个合法的json格式数据,每个字段的意义可以查看上面连接的说明,content后面的test是要发送给用户的数据,这里是群发给所有人
msg="{\"filter\":{\"is_to_all\":true},\"text\":{\"content\":\"test\"},\"msgtype\":\"text\"}\"";
//设置发送消息的参数
StringEntityentity=newStringEntity(msg);
//解决中文乱码的问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
//发送请求
Stringresponse=(String)this.webClient.execute(post,responseHandler);
log.info("returnresponse=====start======");
log.info(response);
log.info("returnresponse=====end======");
returnresponse;
}catch(Exceptione){
log.error("getuserinfoexception",e);
returnnull;
}
}
/**
*@desc发起HTTPGET请求返回数据
*@paramurl
*@return
*@throwsIOException
*@throwsClientProtocolException
*/
privateStringexecuteHttpGet(Stringurl)throwsIOException,ClientProtocolException{
ResponseHandler<?>responseHandler=newBasicResponseHandler();
Stringresponse=(String)this.webClient.execute(newHttpGet(url),responseHandler);
log.info("returnresponse=====start======");
log.info(response);
log.info("returnresponse=====end======");
returnresponse;
}
}
2、Controller和Service层调用
@RequestMapping(value="/testHttpClient",method=RequestMethod.GET)
publicDataMaptest(){
WechatAPIHanderwechatAPIHander=newWechatAPIHander();
//获取access_token
//第一个参数是你appid,第二个参数是你的秘钥,需要根据你的具体情况换
StringaccessToken=wechatAPIHander.getAccessToken("appid","scerpt");
//发送消息
wechatAPIHander.sendMessage(accessToken,"测试数据");
returnnewDataMap().addAttribute("DATA",accessToken);
}
3、结果
假如你关注了微信公众号中看到你刚刚发送的test消息。
HttpClient学习文档:https://pan.baidu.com/s/1miO1eOg
致谢:感谢您的阅读
本文内容总结:
原文链接:https://www.cnblogs.com/0201zcr/p/5893600.html