向微信公众号发送文本消息
首先说下需求,在项目中有时需要时时的知道线上系统的稳定性,防止恶意刷接口,因此就有了线上接口监控系统,时时统计接口在某个时段内调用次数。调用次数超过阀值时进行报警,即向微信公众号发送txt格式消息(接口的详情信息)
1.注册微信公众号(团队的)
注册地址 /
API 开发文档 /wiki/
需要绑定微信号当作管理员(添加应用、管理分组、邀请成员等)
2.实际项目中开发,通过http请求接口
2.1 创建HttpUtils
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import org.;
import org.;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
public class HttpUtils {
private static final Logger LOGGER = ();
public static String get(String url, Map<String, Object> params) {
CloseableHttpClient httpClient = ();
//超时设置
RequestConfig requestConfig = getRequestConfig();
CloseableHttpResponse response = null;
try {
String requestParams = parseParams(params);
String extraUrl = url + ((requestParams) ? "" : "?" + requestParams);
HttpGet get = new HttpGet(extraUrl);
(requestConfig);
response = (get);
HttpEntity entity = ();
return (entity);
} catch (Exception e) {
("访问链接异常[GET] url=" + url, e);
return null;
} finally {
if(response != null) {
try {
();
} catch (IOException e) {
//ignore
}
}
}
}
public static String post(String url, Map<String, Object> params) {
CloseableHttpClient httpClient = ();
RequestConfig requestConfig = getRequestConfig();
CloseableHttpResponse response = null;
try {
HttpPost post = new HttpPost(url);
(requestConfig);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parsePairs(params), "UTF-8");
(entity);
response = (post);
HttpEntity responseEntity = ();
return (responseEntity);
} catch (Exception e) {
("访问链接异常[POST] url=" + url, e);
return null;
} finally {
if(response != null) {
try {
();
} catch (IOException e) {
//ignore
}
}
}
}
public static String post(String url, String text) {
CloseableHttpClient httpClient = ();
RequestConfig requestConfig = getRequestConfig();
CloseableHttpResponse response = null;
try {
HttpPost post = new HttpPost(url);
(requestConfig);
StringEntity entity = new StringEntity(text, "UTF-8");
(entity);
response = (post);
HttpEntity responseEntity = ();
return (responseEntity);
} catch (Exception e) {
("访问链接异常[POST] url=" + url, e);
return null;
} finally {
if(response != null) {
try {
();
} catch (IOException e) {
//ignore
}
}
}
}
/**
* 设置HTTP配置
* 3秒超时
* @return
*/
private static RequestConfig getRequestConfig() {
return ()
.setConnectionRequestTimeout(3000).setConnectTimeout(3000)
.setSocketTimeout(3000).build();
}
@SuppressWarnings("unchecked")
private static String parseParams(Map<String, Object> params) throws Exception{
if((params)) {
return "";
}
StringBuilder sb = new StringBuilder();
for (String key : ()) {
Object value = (key);
if (value == null) {
continue;
}
if (().isArray()) {
for (int i = 0; i < (value); i++) {
String item = ((value, i).toString(), "UTF-8");
(key).append('=').append(item).append('&');
}
} else if(value instanceof List) {
List<Object> items = (List<Object>) value;
for (Object item : items) {
String str = ((), "UTF-8");
(key).append('=').append(str).append('&');
}
} else {
String str = ((), "UTF-8");
(key).append('=').append(str).append('&');
}
}
if (() > 0) {
(() - 1);
}
return ();
}
@SuppressWarnings("unchecked")
private static List<BasicNameValuePair> parsePairs(Map<String, Object> params) {
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
if((params)) {
return list;
}
for (String key : ()) {
Object value = (key);
if (value == null) {
continue;
}
if (().isArray()) {
for (int i = 0; i < (value); i++) {
String item = (value, i).toString();
(new BasicNameValuePair(key, item));
}
} else if(value instanceof List) {
List<Object> items = (List<Object>) value;
for (Object item : items) {
String str = ();
(new BasicNameValuePair(key, str));
}
} else {
String str = ();
(new BasicNameValuePair(key, str));
}
}
return list;
}
}
2.2 创建接口(项目中使用Spring, 写成一个服务供调用比较方便)
MessageData 是我项目中封装的数据对象
public interface WeChatService {
WeChatSendMsgResponse sendMessage(MessageData data);
}
2.3 创建实现类
import ;
import org.;
import org.;
import ;
import ;
import ;
import ;
import ;
import ;
/**
* Created by wanghaiyang on 2016/3/22.
*/
@Service
public class WeChatServiceImpl implements WeChatService {
private static final Logger LOGGER = ();
private static volatile Long sendTimestamp = null;
//参数通过Spring注解读取文件赋值
@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 = ();
//存在且小于一小时,则不报警
if(sendTimestamp != null && (now - sendTimestamp) < 3600*1000) {
return null;
}
//获取access_token
String access_token = getAccessToken();
//获取agentList
List<WeChatAgent> chatAgentList = getAgentList(access_token);
("[WeChatServiceImpl]发送微信消息:" + ());
//发送消息
WeChatSendMsgResponse sendMsgResponse = sendMessage(data, chatAgentList, access_token);
//报警成功,记录时间戳
if("0".equals(())) {
sendTimestamp = ();
}
return sendMsgResponse;
}
/**
* 获取access_token
*
* @return
*/
public String getAccessToken() {
Map<String, Object> params = new HashMap<String, Object>();
("corpid", corpid);
("corpsecret", corpsecret);
String result = (getTokenUrl, params);
Map<String, Object> formatResult = (result, new TypeToken<Map<String, Object>>() {
});
return ("access_token").toString();
}
public List<WeChatAgent> getAgentList(String accessToken) {
Map<String, Object> params = new HashMap<String, Object>();
("access_token", accessToken);
String result = (getAgentUrl, params);
WeChatGetAgentResponse response = (result, );
List<WeChatAgent> list = ();
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 = (0).getAgentid();
//消息内容
String text = ();
//表示是否是保密消息,0表示否,1表示是,默认0
String safe = "0";
Map<String, Object> params = new HashMap<String, Object>();
Map<String, Object> textMap = new HashMap<String, Object>();
("content", ());
("touser", touser);
("toparty", toparty);
("totag", totag);
("msgtype", msgtype);
("agentid", agentid);
("text", textMap);
("safe", safe);
String result = (url, (params));
WeChatSendMsgResponse response = (result, );
return response;
}
}
3.调用发送消息服务
@Autowired
WeChatService weChatService;