向微信公众号发送消息
来源:互联网 发布:微盘 深入浅出node.js 编辑:程序博客网 时间:2024/04/28 16:30
向微信公众号发送文本消息
首先说下需求,在项目中有时需要时时的知道线上系统的稳定性,防止恶意刷接口,因此就有了线上接口监控系统,时时统计接口在某个时段内调用次数。调用次数超过阀值时进行报警,即向微信公众号发送txt格式消息(接口的详情信息)
1.注册微信公众号(团队的)
注册地址 https://qy.weixin.qq.com/
API 开发文档 http://qydev.weixin.qq.com/wiki/index.php
需要绑定微信号当作管理员(添加应用、管理分组、邀请成员等)
2.实际项目中开发,通过http请求接口
2.1 创建HttpUtils
import org.apache.http.HttpEntity;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.utils.URLEncodedUtils;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.util.CollectionUtils;import org.springframework.util.StringUtils;import java.io.IOException;import java.lang.reflect.Array;import java.net.URLEncoder;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.Map;public class HttpUtils { private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class); public static String get(String url, Map<String, Object> params) { CloseableHttpClient httpClient = HttpClients.createDefault(); //超时设置 RequestConfig requestConfig = getRequestConfig(); CloseableHttpResponse response = null; try { String requestParams = parseParams(params); String extraUrl = url + (StringUtils.isEmpty(requestParams) ? "" : "?" + requestParams); HttpGet get = new HttpGet(extraUrl); get.setConfig(requestConfig); response = httpClient.execute(get); HttpEntity entity = response.getEntity(); return EntityUtils.toString(entity); } catch (Exception e) { LOGGER.error("访问链接异常[GET] url=" + url, e); return null; } finally { if(response != null) { try { response.close(); } catch (IOException e) { //ignore } } } } public static String post(String url, Map<String, Object> params) { CloseableHttpClient httpClient = HttpClients.createDefault(); RequestConfig requestConfig = getRequestConfig(); CloseableHttpResponse response = null; try { HttpPost post = new HttpPost(url); post.setConfig(requestConfig); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parsePairs(params), "UTF-8"); post.setEntity(entity); response = httpClient.execute(post); HttpEntity responseEntity = response.getEntity(); return EntityUtils.toString(responseEntity); } catch (Exception e) { LOGGER.error("访问链接异常[POST] url=" + url, e); return null; } finally { if(response != null) { try { response.close(); } catch (IOException e) { //ignore } } } } public static String post(String url, String text) { CloseableHttpClient httpClient = HttpClients.createDefault(); RequestConfig requestConfig = getRequestConfig(); CloseableHttpResponse response = null; try { HttpPost post = new HttpPost(url); post.setConfig(requestConfig); StringEntity entity = new StringEntity(text, "UTF-8"); post.setEntity(entity); response = httpClient.execute(post); HttpEntity responseEntity = response.getEntity(); return EntityUtils.toString(responseEntity); } catch (Exception e) { LOGGER.error("访问链接异常[POST] url=" + url, e); return null; } finally { if(response != null) { try { response.close(); } catch (IOException e) { //ignore } } } } /** * 设置HTTP配置 * 3秒超时 * @return */ private static RequestConfig getRequestConfig() { return RequestConfig.custom() .setConnectionRequestTimeout(3000).setConnectTimeout(3000) .setSocketTimeout(3000).build(); } @SuppressWarnings("unchecked") private static String parseParams(Map<String, Object> params) throws Exception{ if(CollectionUtils.isEmpty(params)) { return ""; } StringBuilder sb = new StringBuilder(); for (String key : params.keySet()) { Object value = params.get(key); if (value == null) { continue; } if (value.getClass().isArray()) { for (int i = 0; i < Array.getLength(value); i++) { String item = URLEncoder.encode(Array.get(value, i).toString(), "UTF-8"); sb.append(key).append('=').append(item).append('&'); } } else if(value instanceof List) { List<Object> items = (List<Object>) value; for (Object item : items) { String str = URLEncoder.encode(item.toString(), "UTF-8"); sb.append(key).append('=').append(str).append('&'); } } else { String str = URLEncoder.encode(value.toString(), "UTF-8"); sb.append(key).append('=').append(str).append('&'); } } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); } @SuppressWarnings("unchecked") private static List<BasicNameValuePair> parsePairs(Map<String, Object> params) { List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); if(CollectionUtils.isEmpty(params)) { return list; } for (String key : params.keySet()) { Object value = params.get(key); if (value == null) { continue; } if (value.getClass().isArray()) { for (int i = 0; i < Array.getLength(value); i++) { String item = Array.get(value, i).toString(); list.add(new BasicNameValuePair(key, item)); } } else if(value instanceof List) { List<Object> items = (List<Object>) value; for (Object item : items) { String str = item.toString(); list.add(new BasicNameValuePair(key, str)); } } else { String str = value.toString(); list.add(new BasicNameValuePair(key, str)); } } return list; }}
2.2 创建接口(项目中使用Spring, 写成一个服务供调用比较方便)
MessageData 是我项目中封装的数据对象
public interface WeChatService { WeChatSendMsgResponse sendMessage(MessageData data);}
2.3 创建实现类
import com.google.gson.reflect.TypeToken;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;/** * Created by wanghaiyang on 2016/3/22. */@Servicepublic class WeChatServiceImpl implements WeChatService { private static final Logger LOGGER = LoggerFactory.getLogger(WeChatServiceImpl.class); private static volatile Long sendTimestamp = null; //参数通过Spring注解读取const.properties文件赋值 @Value("${WeChat_Gettoken_Url}") private String getTokenUrl; @Value("${WeChat_CropID}") private String corpid; @Value("${WeCaht_Secret}") private String corpsecret; @Value("${WeChat_GetAgentList_Url}") private String getAgentUrl; @Value("${WeChat_SendMsg_url}") private String sendMsgUrl; /** * 向公众号发送消息 */// @Async public WeChatSendMsgResponse sendMessage(MessageData data) { Long now = System.currentTimeMillis(); //存在且小于一小时,则不报警 if(sendTimestamp != null && Math.abs(now - sendTimestamp) < 3600*1000) { return null; } //获取access_token String access_token = getAccessToken(); //获取agentList List<WeChatAgent> chatAgentList = getAgentList(access_token); LOGGER.info("[WeChatServiceImpl]发送微信消息:" + data.toString()); //发送消息 WeChatSendMsgResponse sendMsgResponse = sendMessage(data, chatAgentList, access_token); //报警成功,记录时间戳 if("0".equals(sendMsgResponse.getErrcode())) { sendTimestamp = System.currentTimeMillis(); } return sendMsgResponse; } /** * 获取access_token * * @return */ public String getAccessToken() { Map<String, Object> params = new HashMap<String, Object>(); params.put("corpid", corpid); params.put("corpsecret", corpsecret); String result = HttpUtils.get(getTokenUrl, params); Map<String, Object> formatResult = GsonUtils.fromJson(result, new TypeToken<Map<String, Object>>() { }); return formatResult.get("access_token").toString(); } public List<WeChatAgent> getAgentList(String accessToken) { Map<String, Object> params = new HashMap<String, Object>(); params.put("access_token", accessToken); String result = HttpUtils.get(getAgentUrl, params); WeChatGetAgentResponse response = GsonUtils.fromJson(result, WeChatGetAgentResponse.class); List<WeChatAgent> list = response.getAgentlist(); return list; } public WeChatSendMsgResponse sendMessage(MessageData data, List<WeChatAgent> chatAgentList, String accessToken) { String url = sendMsgUrl + accessToken; //成员ID列表 特殊情况:指定为@all,则向关注该企业应用的全部成员发送 String touser = "@all"; //部门ID列表 String toparty = "1"; //标签ID列表 String totag = ""; //消息类型 String msgtype = "text"; //企业应用的id 发送到 int agentid = chatAgentList.get(0).getAgentid(); //消息内容 String text = data.toString(); //表示是否是保密消息,0表示否,1表示是,默认0 String safe = "0"; Map<String, Object> params = new HashMap<String, Object>(); Map<String, Object> textMap = new HashMap<String, Object>(); textMap.put("content", data.toString()); params.put("touser", touser); params.put("toparty", toparty); params.put("totag", totag); params.put("msgtype", msgtype); params.put("agentid", agentid); params.put("text", textMap); params.put("safe", safe); String result = HttpUtils.post(url, GsonUtils.toJson(params)); WeChatSendMsgResponse response = GsonUtils.fromJson(result, WeChatSendMsgResponse.class); return response; }}
3.调用发送消息服务
@Autowired WeChatService weChatService;
1 0
- 向微信公众号发送消息
- 微信公众号发送模板消息
- 微信公众号发送模板消息
- 微信公众号发送模板消息
- 向微信公众号发送么个特地消息给么个人
- 微信公众号的开发之 向用户发送消息(三)
- 向微信发送消息
- 微信公众号开发系列-发送客服消息
- 微信公众号开发之[发送模板消息]
- 使用shell通过微信公众号发送模板消息
- 微信公众号发送中奖模板消息
- 微信公众号开发(七)发送客服消息
- 微信公众号开发(Java) ---- 客服消息发送
- 微信公众号发送模板消息接口
- 【微信公众平台开发】利用客服接口向用户发送网页授权的消息
- 微信公众平台发送模板消息
- 微信公众平台发送模板消息
- 微信公众平台 发送模板消息
- 窗口句柄
- Android LayoutFlater详解
- 【数据结构与算法】String大数加减乘除(非负整数)
- iOS开发:多线程之线程安全
- Neural Network中的Activation function作用
- 向微信公众号发送消息
- Android系统属性prop
- 利用RFM模型做电商客户价值分析
- hdu4289-网络流
- SQLite 浅谈SQLite的虚拟机
- js 处理日期格式化
- Mysql(一) - 数据库和表的基本操作 及 数值类型
- android平台下的aes加密和java平台下的运行结果不同的解决办法
- 形态学图像处理