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;/*** Created by zhengcanrui on 16/9/20.*/
public classWechatAPIHander {/*** 获取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}";privateHttpClient webClient;private Log log =LogFactory.getLog(getClass());public void initWebClient(String proxyHost, intproxyPort){this.initWebClient();if(webClient != null && !StringUtils.isEmpty(proxyHost)){
HttpHost proxy= newHttpHost(proxyHost, proxyPort);
webClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
}/*** @desc 初始化创建 WebClient*/
public voidinitWebClient() {
log.info("initWebClient start....");try{
PoolingClientConnectionManager tcm= newPoolingClientConnectionManager();
tcm.setMaxTotal(10);
SSLContext ctx= SSLContext.getInstance("TLS");
X509TrustManager tm= newX509TrustManager() {
@Overridepublic void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throwsjava.security.cert.CertificateException {
}
@Overridepublic void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throwsjava.security.cert.CertificateException {
}
@Overridepublicjava.security.cert.X509Certificate[] getAcceptedIssuers() {return new java.security.cert.X509Certificate[0];
}
};
ctx.init(null, new X509TrustManager[] { tm }, null);
SSLSocketFactory ssf= newSSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Scheme sch= new Scheme("https", 443, ssf);
tcm.getSchemeRegistry().register(sch);
webClient= newDefaultHttpClient(tcm);
}catch(Exception ex) {
log.error("initWebClient exception", ex);
}finally{
log.info("initWebClient end....");
}
}/*** @desc 获取授权token
*@paramappid
*@paramsecret
*@return
*/
publicString 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);
}returnaccessToken;
}/*** @desc 推送信息
*@paramtoken
*@parammsg
*@return
*/
publicString sendMessage(String token,String msg){try{
log.info("\n\nsendMessage start.token:"+token+",msg:"+msg);
String url= MessageFormat.format(this.sendMsgUrl, token);
HttpPost post= newHttpPost(url);
ResponseHandler> responseHandler = newBasicResponseHandler();//这里必须是一个合法的json格式数据,每个字段的意义可以查看上面连接的说明,content后面的test是要发送给用户的数据,这里是群发给所有人
msg = "{\"filter\":{\"is_to_all\":true},\"text\":{\"content\":\"test\"},\"msgtype\":\"text\"}\"";//设置发送消息的参数
StringEntity entity = newStringEntity(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======");returnresponse;
}catch(Exception e) {
log.error("get user info exception", e);return null;
}
}/*** @desc 发起HTTP GET请求返回数据
*@paramurl
*@return*@throwsIOException
*@throwsClientProtocolException*/
private String executeHttpGet(String url) throwsIOException, ClientProtocolException {
ResponseHandler> responseHandler = newBasicResponseHandler();
String response= (String) this.webClient.execute(newHttpGet(url), responseHandler);
log.info("return response=====start======");
log.info(response);
log.info("return response=====end======");returnresponse;
}
}