1.首先你要有个手机号 申请个测试信息
2.然后就可以开始写了
a.获取用户accessToken
public String getToken(String appid, String secrect) {
String urlStr = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid
+ "&secret=" + secrect;
String res = requestInterface(urlStr);
JSONObject jsonObj = JSONObject.fromObject(res);
return (String) jsonObj.get("access_token");
}
b.通过token获取用户列表
public List<String> getUserId(String token) {
String requst_url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + token + "&next_openid=";
List<String> userList = new ArrayList<String>();
String res = requestInterface(requst_url);
JSONObject dataObj = JSONObject.fromObject(res);
JSONObject openidObj = JSONObject.fromObject(dataObj.get("data"));
String[] openidStr = openidObj.get("openid").toString().replace("[", "").replace("]", "").split(",");
for (String openid : openidStr) {
userList.add(openid.replaceAll("\"", ""));
}
return userList;
}
c.发送模板消息接口
public boolean do_push_Template(String token, String userId, String template_id, String url, String data) {
String requst_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
Map<String, Object> map = new HashMap<String, Object>();
map.put("touser", userId);
map.put("template_id", template_id);
map.put("url", url);
map.put("data", data);
String response = HttpRequest.sendPost2(requst_url, map,null);
JSONObject responseObj = JSONObject.fromObject(response);
String responseFlag = responseObj.get("errmsg").toString();
System.out.println("response:" + responseFlag);
if (responseFlag.equals("ok")) {
return true;
} else {
return false;
}
3.把三个接口串起来就可以实现微信推送功能了
String token = new WechatPush().getToken("xx", "xx");
List<String> list = new WechatPush().getUserId(token);
Map<String,Object> dataMap=new HashMap<String,Object>();
dataMap.put("All_testcases", 52);
dataMap.put("Pass_testcases", 52);
dataMap.put("Fail_testcases", 52);
dataMap.put("Error_testcases", 52);
dataMap.put("Pass_rate", 52);
dataMap.put("Report_name", 52);
String data=JSONObject.fromObject(dataMap).toString();
System.out.println(data);
boolean flag=new WechatPush().do_push_Template(token, list.get(0), "xx",
"https://api.weixin.qq.com/cgi-bin/message",data );
System.out.println(flag);
4.文章中的HttpRequest.sendPost2可以访问文章 关于要访问http和https地址,post访问的参数map对象