微信java开发之实现微信主动推送消息
1.拉取access_token
2.拉取用户信息
3.主动推送消息
4.接口貌似要申请权限
5.依赖httpclient4.2.3 和jackson 2.2.1
public class WeixinAPIHelper {
/**
* 获取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/send?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() {
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
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);
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("sendMessage start.token:"+token+",msg:"+msg);
String url = MessageFormat.format(this.sendMsgUrl, token);
HttpPost post = new HttpPost(url);
ResponseHandler<?> responseHandler = new BasicResponseHandler();
StringEntity entity = new StringEntity(msg);
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 拉取用户信息
* @param token
* @param openid
* @return
*/
public WeixinOpenUser getUserInfo(String token, String openid) {
try {
log.info("getUserInfo start.{token:" + token + ",openid:" + openid + "}");
String url = MessageFormat.format(this.getUserInfoUrl, token, openid);
String response = executeHttpGet(url);
JsonNode json = JsonUtils.read(response);
if (json.get("openid") != null) {
WeixinOpenUser user = new WeixinOpenUser();
user.setOpenUserId(json.get("openid").asText());
user.setState(json.get("subscribe").asText());
if ("1".equals(user.getState())) {
user.setUserName(json.get("nickname").asText());
user.setSex(json.get("sex").asText());
user.setCity(json.get("city").asText());
user.setLanguage(json.get("language").asText());
}
return user;
}
} 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;
}
}
微信java开发之实现微信主动推送消息的更多相关文章
- 微信公众平台主动推送消息(asp.net)
/// <summary> /// MD5 32位加密 /// </summary> /// <param name=" ...
- Websocket实现Java后台主动推送消息到前台
写在前面 需求: 项目测试, 缺少用户登录失败给admin推送消息, 想到这个方式, 当用户登录失败时, admin用户会在页面看到咣咣乱弹的alert. 正文 pom.xml <!-- web ...
- 3行java代码实现百度站长主动推送
个人博客 地址:http://www.wenhaofan.com/article/push-link-seo 介绍 当网站新增了一个网页之后,此时这个网页是不能够立马被百度收录的,如果想以最快的速度被 ...
- python 全栈开发,Day131(向app推送消息,玩具端消息推送)
先下载github代码,下面的操作,都是基于这个版本来的! https://github.com/987334176/Intelligent_toy/archive/v1.4.zip 注意:由于涉及到 ...
- php简陋版实现微信公众号主动推送消息
推荐一个网站www.itziy.com csdn免积分下载器.pudn免积分下载器.51cto免积分下载器www.verypan.com 百度网盘搜索引擎www.94cto.com 编程相关视频教程. ...
- 基于SuperSocket的IIS主动推送消息给android客户端
在上一篇文章<基于mina框架的GPS设备与服务器之间的交互>中,提到之前一直使用superwebsocket框架做为IIS和APP通信的媒介,经常出现无法通信的问题,必须一天几次的手动回 ...
- 微信小程序简单的推送消息流程
1.进入开发设置-消息推送,启用消息推送 url: 启用并设置消息推送配置后,用户发给小程序的消息以及开发者需要的事件推送,都将被微信转发至该服务器地址中. 2.创建消息模板. 3.WXML代码: 4 ...
- Django2.0.4 + websocket 实现实时通信,主动推送,聊天室及客服系统
webSocket是一种在单个TCP连接上进行全双工通信的协议. webSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据.在WebSocket API中,浏览器 ...
- 为美多商城(Django2.0.4)添加基于websocket的实时通信,主动推送,聊天室及客服系统
原文转载自「刘悦的技术博客」https://v3u.cn/a_id_67 websocket是个啥? webSocket是一种在单个TCP连接上进行全双工通信的协议 webSocket使得客户端和服务 ...
随机推荐
- linux内核情景分析之execve()
用来描述用户态的cpu寄存器在内核栈中保存情况.可以获取用户空间的信息 struct pt_regs { long ebx; //可执行文件路径的指针(regs.ebx中 long ecx; //命令 ...
- Linux内存管理之mmap详解 【转】
转自:http://blog.chinaunix.net/uid-26669729-id-3077015.html 一. mmap系统调用 1. mmap系统调用 mmap将一个文件或者其它对象映射进 ...
- mogilefsdBUG mogilefsd[15624]: crash log: Modification of a read-only value attempted at /usr/local/share/perl5/Sys/Syscall.pm line 227
mogilefsd[15624]: crash log: Modification of a read-only value attempted at /usr/local/share/perl5/S ...
- PE文件从文件加载到内存,再从内存读取,然后存盘到文件
// mem.cpp : 定义控制台应用程序的入口点. //PE文件从文件加载到内存,再从内存读取,然后存盘到文件 #include "stdafx.h" #include < ...
- net页面生命周期
ASP.NET 页运行时,此页将经历一个生命周期,在生命周期中将执行一系列处理步骤.这些步骤包括初始化.实例化控件.还原和维护状态.运行事件处理程序代码以及进行呈现.了解页的生命周期非常重要,这样就能 ...
- Codeforces 600E - Lomsat gelral(树上启发式合并)
600E - Lomsat gelral 题意 给出一颗以 1 为根的树,每个点有颜色,如果某个子树上某个颜色出现的次数最多,则认为它在这课子树有支配地位,一颗子树上,可能有多个有支配的地位的颜色,对 ...
- [JSOI2009] 有趣的游戏
1444: [Jsoi2009]有趣的游戏 Time Limit: 10 Sec Memory Limit: 64 MBSubmit: 1800 Solved: 645[Submit][Statu ...
- 代理模式(Proxy)--动态代理(JDK)
在是上一篇博客中实现了静态代理. 在上篇的结尾提到了一个问题: 思考:如果我们下需要对火车,自行车实现相同的代理,我们又该如何实现呢? 这篇博客就来解决这个问题: 解决这类问题需要用到动态代理技术,实 ...
- Netbeans 中部署运行Webservice出错
错误如下 at java.lang.StackTraceElement at public java.lang.StackTraceElement[] java.lang.Throwable.ge ...
- 4.NFC前台调度系统
使用目的:当前Activity能直接响应NFC标签,而不需要用户在choose所有能处理的Activity. 使用步骤: 第一步:在onCreate()方法中,创建一个PendingIntent对象 ...