微信公众号开发如何群发消息
- 获取微信提供的接口文件
public static String url3 = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID";
- 传入appid和appsecret然后获取token
public static AccessToken getAccessToken(String appid, String appsecret) {
String APPID = appid;
String APPSECRET =appsecret ;
String Access_tokenString = null;
AccessToken accessTokenInfo=null;
String getAccesstokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ APPID + "&secret=" + APPSECRET;
Access_tokenString = WeixinHttpRequestUtil.httpRequest(getAccesstokenUrl,
"GET", null);
if (Access_tokenString.contains("access_token")) {
accessTokenInfo = JSON.parseObject(Access_tokenString,
AccessToken.class);
System.out.println( accessTokenInfo.toString());
return accessTokenInfo;
}
return accessTokenInfo ;
}
- 替换微信接口中的ACCESS_TOKEN,NEXT_OPENID可以为空,默认查询所有的
String newurl3 = url3.replace("ACCESS_TOKEN", accessToken.getAccess_token());
String url3=newurl3.replaceAll("NEXT_OPENID", "");
- 向微信端发送get请求,下面是我贴出了我工具类中的get方法,直接掉吧上面替换后拿到的url3当作参数传进去就ok了
String jsonThree=ToolsUtil.get(url3);
public static String get(String url){
try {
URL urlObj = new URL(url);
//开链接
URLConnection connection = urlObj.openConnection();
InputStream is = connection.getInputStream();
byte[] b = new byte[1024];
int len;
StringBuilder sb = new StringBuilder();
while ((len = is.read(b)) != -1) {
sb.append(new String(b,0,len));
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
- 解析返回的jsoN格式,获取count值,如果是0 的话不忘下面走,如果不是继续往下面走用List去接受拿到的openid,然后向指定用户发送消息(向指定用户发送消息的方法我上一篇博客中有写到,可以参考一下)
String str=jsonThree;
Gson gson=new Gson();
Map map = gson.fromJson(str, Map.class);
String data2 =map.get("count").toString();
System.out.println("data2=="+data2);
if(!data2.equals("0.0")){
System.out.println("123");
}else{
System.out.println("234");
}
String data = map.get("data").toString();
System.out.println("data="+data);
Type type=new TypeToken<Map<String,List<String>>>(){}.getType();
Map<String,List<String>> result = gson.fromJson(data, type);
List<String> list=result.get("openid");
for(int i=0;i< list.size();i++){
System.out.println("list=="+list.get(i));
}
System.out.println("result=="+result.get("openid").toString());
}
个人新手,有问题提出来,大家共同探讨,谢谢