微信公众号实现消息推送
public JsonResult sendMessage(String content) {//获得令牌 // String accessToken = "21_UrWTu7IQt5N5KFlnPRdI4ec4C3vPxyvchJQf5E-yBmFED-uEeT6CF5eLpj9yFY6wloZAP6bYmCBR784_wACmU_MZX70JzumXu7XjT58ykCSNkDUW1qFh3JgJ7qJAtLBuwXDhEAbLYZIEF9cmCUVcAGAOGH";WxAccesstoken wxAccesstoken = wxAccesstokenMapper.selectByPrimaryKey("E1C969101C0000008E00000000366000");String accessToken = wxAccesstoken.getAccessToken();String url = TemplateMessage_Url.replace("ACCESS_TOKEN",accessToken);//调用接口进行发送try {Map<String, String> headers = new HashMap<>();headers.put("Content-Type","application/json;charset=utf-8");HttpResponse res = HttpUtils.doPost2(url,"",null,headers,null, content);String returnJson = EntityUtils.toString(res.getEntity());return JsonResult.success(returnJson);} catch (Exception e) {e.printStackTrace();}return null;}
工具类
package com.zt.oa.util;import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair;import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.Map;public class HttpUtils {/*** get** @param host* @param path* @param method* @param headers* @param querys* @return* @throws Exception*/public static HttpResponse doGet(String host, String path, String method,Map<String, String> headers,Map<String, Object> querys)throws Exception {HttpClient httpClient = wrapClient(host);HttpGet request = new HttpGet(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}return httpClient.execute(request);}/*** post form** @param host* @param path* @param method* @param headers* @param querys* @param bodys* @return* @throws Exception*/public static HttpResponse doPost(String host, String path, String method,Map<String, String> headers,Map<String, Object> querys,Map<String, String> bodys)throws Exception {HttpClient httpClient = wrapClient(host);HttpPost request = new HttpPost(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (bodys != null) {List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();for (String key : bodys.keySet()) {nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));}UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");request.setEntity(formEntity);}return httpClient.execute(request);}/*** Post String** @param host* @param path* @param method* @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPost(String host, String path, String method,Map<String, String> headers,Map<String, Object> querys,String body)throws Exception {HttpClient httpClient = wrapClient(host);HttpPost request = new HttpPost(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (body.toString().indexOf(" ")<0 /*StringUtils.isNotBlank(body)*/) {request.setEntity(new StringEntity(body, "utf-8"));}return httpClient.execute(request);}/*** Post String** @param host* @param path* @param method* @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPost2(String host, String path, String method,Map<String, String> headers,Map<String, Object> querys,String body)throws Exception {HttpClient httpClient = wrapClient(host);HttpPost request = new HttpPost(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}request.setEntity(new StringEntity(body, "utf-8"));return httpClient.execute(request);}/*** Post stream** @param host* @param path* @param method* @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPost(String host, String path, String method,Map<String, String> headers,Map<String, Object> querys,byte[] body)throws Exception {HttpClient httpClient = wrapClient(host);HttpPost request = new HttpPost(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (body != null) {request.setEntity(new ByteArrayEntity(body));}return httpClient.execute(request);}/*** Put String* @param host* @param path* @param method* @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPut(String host, String path, String method,Map<String, String> headers,Map<String, Object> querys,String body)throws Exception {HttpClient httpClient = wrapClient(host);HttpPut request = new HttpPut(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (body.toString().indexOf(" ")<0/*StringUtils.isNotBlank(body)*/) {request.setEntity(new StringEntity(body, "utf-8"));}return httpClient.execute(request);}/*** Put stream* @param host* @param path* @param method* @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPut(String host, String path, String method,Map<String, String> headers,Map<String, Object> querys,byte[] body)throws Exception {HttpClient httpClient = wrapClient(host);HttpPut request = new HttpPut(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (body != null) {request.setEntity(new ByteArrayEntity(body));}return httpClient.execute(request);}/*** Delete** @param host* @param path* @param method* @param headers* @param querys* @return* @throws Exception*/public static HttpResponse doDelete(String host, String path, String method,Map<String, String> headers,Map<String, Object> querys)throws Exception {HttpClient httpClient = wrapClient(host);HttpDelete request = new HttpDelete(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}return httpClient.execute(request);}private static String buildUrl(String host, String path, Map<String, Object> querys) throws UnsupportedEncodingException {StringBuilder sbUrl = new StringBuilder();sbUrl.append(host);if (path.toString().indexOf(" ")<0/*!StringUtils.isBlank(path)*/) {sbUrl.append(path);}if (null != querys) {StringBuilder sbQuery = new StringBuilder();for (Map.Entry<String, Object> query : querys.entrySet()) {if (0 < sbQuery.length()) {sbQuery.append("&");}if (query.getKey().indexOf(" ")>0/*StringUtils.isBlank(query.getKey())*/ &&String.valueOf(query.getValue()).indexOf(" ")<0 /*!StringUtils.isBlank(query.getValue())*/) {sbQuery.append(query.getValue());}if (query.getKey().indexOf(" ")>0/*!StringUtils.isBlank(query.getKey())*/) {sbQuery.append(query.getKey());if (String.valueOf(query.getValue()).indexOf(" ")<0/*!StringUtils.isBlank(query.getValue())*/) {sbQuery.append("=");sbQuery.append(URLEncoder.encode(String.valueOf(query.getValue()), "utf-8"));}}}if (0 < sbQuery.length()) {sbUrl.append("?").append(sbQuery);}}return sbUrl.toString();}private static HttpClient wrapClient(String host) {HttpClient httpClient = new DefaultHttpClient();if (host.startsWith("https://")) {sslClient(httpClient);}return httpClient;}private static void sslClient(HttpClient httpClient) {try {SSLContext ctx = SSLContext.getInstance("TLS");X509TrustManager tm = new X509TrustManager() {public X509Certificate[] getAcceptedIssuers() {return null;}public void checkClientTrusted(X509Certificate[] xcs, String str) {}public void checkServerTrusted(X509Certificate[] xcs, String str) {}};ctx.init(null, new TrustManager[] { tm }, null);SSLSocketFactory ssf = new SSLSocketFactory(ctx);ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);ClientConnectionManager ccm = httpClient.getConnectionManager();SchemeRegistry registry = ccm.getSchemeRegistry();registry.register(new Scheme("https", 443, ssf));} catch (KeyManagementException ex) {throw new RuntimeException(ex);} catch (NoSuchAlgorithmException ex) {throw new RuntimeException(ex);}} }
测试controller
/*** 测试* @return*/@GetMapping("/sendTest")public JsonResult testSendMessage(){//创建消息发送实体对象TemplateMessage templateMessage=new TemplateMessage(); // templateMessage.setUrl("www.baidu.com");templateMessage.setTouser("oZ5gZ000ftRiKIbZplGit8x0f_M0");templateMessage.setTemplate_id(templateId);//设置模板标题Content first=new Content();first.setValue("您好!您发起了流程审批");first.setColor("#000");//设置模板内容Content keyword1=new Content();keyword1.setValue("尹东伟发起的车采购审批");keyword1.setColor("#000");//设置模板位置Content keyword2=new Content();keyword2.setValue("发起");keyword2.setColor("#000");//设置设备Content keyword3=new Content();keyword3.setValue("尹东伟");keyword3.setColor("#000");//设置时间Content keyword4=new Content();SimpleDateFormat format=new SimpleDateFormat("yyyy年MM月dd日");String format1 = format.format(new Date());keyword4.setValue(format1);keyword4.setColor("#000");//设置跳转内容Content remark=new Content();remark.setValue("请您及时关注流程动态");remark.setColor("#000");//创建模板信息数据对象Data data=new Data();data.setFirst(first);data.setKeyword1(keyword1);data.setKeyword2(keyword2);data.setKeyword3(keyword3);data.setKeyword4(keyword4);data.setRemark(remark);templateMessage.setData(data);//将封装的数据转成JSONString jsonString = JSON.toJSONString(templateMessage);logger.info(jsonString);JsonResult jsonResult = wxMessageService.sendMessage(jsonString);return jsonResult;}
微信公众号实现消息推送相关推荐
- 实现微信公众号H5消息推送的超级详细步骤
前言 前段时间在项目中做了一个给H5消息推送的功能,特此记录一下,感兴趣或者有需要的小伙伴可以查阅一下,因为其实代码并不难,我觉得对于初学者来说难的是一些概念和具体实现的过程,所以我会先使用微信提供的 ...
- 微信公众号模板消息推送问题汇总
总结:经常遇到的微信模版消息推送返回失败情况! 1.{"errcode":40037,"errmsg":"invalid template_id hi ...
- Java对接微信公众号模板消息推送(架包WxJava)
内容有点多,请耐心! 最近公司的有这个业务需求,又很凑巧让我来完成: 首先想要对接,先要一个公众号,再就是开发文档了:https://developers.weixin.qq.com/doc/offi ...
- 该微信用户未开启“公众号安全助手”的消息接收功能,请先开启后再绑定,Java微信公众号开发消息推送公众号用户绑定问题 的解决办法
问题概述 在进行微信公众号开发的时候遇到的这个问题,通过Web开发公众号的模板消息推送,在调试的过程中,需要进行开发者接口联调&调试,在调试之前需要将当前的公众号与用户的微信号进行绑定, 绑定 ...
- Java对接微信公众号模板消息推送
最近公司的有这个业务需求,又很凑巧让我来完成: 首先想要对接,先要一个公众号,再就是开发文档了:https://developers.weixin.qq.com/doc/offiaccount/Get ...
- 微信公众号开发消息推送以及图文推送
今天给大家分享的关注公众号自动推送图文消息,以及做一个超牛逼的机器人. 先看看效果. 发错图了...这是我昨天开发的一款机器人chu了会骂人啥都不会了.我今天将它词库进行了更新和升级,接入了http: ...
- Nodejs + express 开发微信公众号模板消息推送功能
第一步:申请测试号 1.打开微信测试号申请平台 http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login 2.点击"登录&q ...
- 微信公众号模板消息推送(附上完整代码)
官方文档 会用到的调用函数 import logging import requests import time from pickle import dumps, loadsfrom request ...
- 【Java中实现微信公众号模板消息推送】
主要流程: 1.在微信公众测试平台上注册账号,关注测试公众号,新增消息模板 2.拿到需要的参数openId appId appsecret 模板Id后进行开发 微信公众平台测试号管理地址 https: ...
- 微信公众号模板消息推送(PHP)
1.发送模板消息 public function send_notice(){$access_token = '';//模板消息$json_template = $this->json_temp ...
最新文章
- WinForm下ComboBox获取绑定对象集的SelectedValue补充
- vue ui无效_vue开发中,父组件添加scoped之后。解决在父组件中无法修改子组件样式问题。...
- php抓取新浪微博数据抓取,php利用curl抓取新浪微博内容示例
- android 支付宝沙箱测试环境,Android支付宝沙箱环境使用教程
- postgres xshell copy 命令 内存溢出_良心国产工具,比Xshell好用还免费!
- 改写DataCogs在MOSS列表中实现三级联动字段
- 物体检测方法总结(下)
- LuoguP1131 [ZJOI2007]时态同步
- 中考计算机考试试题山西注意事项,2021年山西省中考考试注意事项(3)
- ubuntu php 扩展目录_MacOS搭建PHP开发环境
- 路由交换机管理密码篇
- WINDOWS常用端口
- 【T+】win10/win11系统安装畅捷通T+Cloud专属云18.0
- labelme转VOC2007格式
- php 微信公众号登录,PHP 实现微信公众号网页授权登录
- 【防火墙_动态路由-OSPF】
- html div鼠标选中状态,CSS鼠标移动div时如何避免选中div中的文字
- TikTok搬运视频怎么做,搬运怎样的视频最好
- Xrm.WebApi 多对多关系处理
- Openstack-实践4.Manila 部署及功能验证