利用java开发微信实现微信主动推送消息实例

这篇文章主要介绍了利用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;
 }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


网页授权获取用户信息的方法
报错config:invalid signature的解决方案
微信开发百思不得姐实战教程
详解微信开发input输入框
教你libco是如何支撑巨大数据信息量的
微信二次开发之文本消息请求与发送
微信开发H5轻游戏
scroll-view完成列表页的方法详解
Java微信开发之自定义菜单的创建
微信开发之input控件的实例详解
微信开发Emoji表情的实例教程
微信开发中详解textarea的使用方法
微信开发中使元素占满全屏的方法介绍
微信开发之数据访问的方法详解
微信二次开发之各类型消息封装
微信开发之数据库操作
如何获取微信好友的地理位置信息
分享3款微信开发开源框架
微信开发之获取服务器IP
微信开发之公交换乘功能代码详解