微信一次性订阅消息
第一步:需要用户同意授权,获取一次给用户推送一条订阅模板消息的机会
可以看微信公众号的文档
点击打开链接
第二步:通过API推送订阅模板消息给到授权微信用户
我这发一下具体发送的方法,跟我自己以前用的不太一样 ,在此记录一下
//推送订阅模板消息url String sendMsgUrl = "https://api.weixin.qq.com/cgi-bin/message/template/subscribe?access_token=access_token"; JSONObject json = new JSONObject(); json.put("touser",openid); //订阅消息模板ID,登录公众平台后台,在接口权限列表处可查看订阅模板ID json.put("template_id",""); json.put("url",""); //消息体 String msgStr = "{\"touser\":\"" + openid + "\",\"data\":{\"content\":{\"color\":\"#173177\",\"value\":\"通知内容\"}},\"template_id\":\"template_id\",\"title\":\"中奖通知\",\"scene\":\"1000\",\"url\":\"https://\"}"; logger.info(msgStr); //通过API推送订阅模板消息给到授权微信用户 String noticeResult= HttpClientUtil.sendPost(sendMsgUrl,msgStr);
/**
* 向指定 URL 发送POST方法的请求 * * @param url *发送请求的 URL * @param param *请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所代表远程资源的响应结果 */ public static String sendPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); //设置通用的请求属性 conn.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0)"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), "utf-8"); out = new PrintWriter(outWriter); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { in = new BufferedReader(new InputStreamReader(conn.getInputStream())); result += line; } } catch (Exception e) { e.printStackTrace(); } //使用finally块来关闭输出流、输入流 finally{ try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } } catch(IOException ex){ ex.printStackTrace(); } } return result; }
【微信一次性订阅消息】
推荐阅读
- 基于微信小程序带后端ssm接口小区物业管理平台设计
- 员工的微信朋友圈是公司的宣传阵地吗()
- FBI怎么和恐怖分子谈判
- 分享!如何分分钟实现微信扫二维码调用外部浏览器打开指定页面的功能
- 微信小程序基础知识
- 使用Promise对微信小程序wx.request请求方法进行封装
- Vue组件之事件总线和消息发布订阅详解
- 茶事|茶事 | 单丛里的一泡奇葩
- Redis——发布订阅/消息队列
- 微信小程序请求接口格式