6.8.1 查询分组
通过查询分组接口能够获取到公众账号的分组列表,列表中包含了每个分组的id、名称和分组内的用户数。
1.接口描述
查询分组接口的请求地址如下:
- https://api.weixin.qq.com/cgi-bin/groups/get?access_token=ACCESS_TOKEN
通过发送HTTPS GET请求调用该接口,正确时返回的JSON结果如下:
- {
- "groups": [
- {
- "id": 0,
- "name": "未分组",
- "count": 72596
- },
- {
- "id": 1,
- "name": "黑名单",
- "count": 0
- },
- {
- "id": 2,
- "name": "星标组",
- "count": 8
- },
- {
- "id": 104,
- "name": "公司内部",
- "count": 50
- }
- ]
- }
上述JSON结果中的参数说明如表6-10所示。
表6-10 查询分组接口返回参数说明
接口调用错误时,返回的JSON结果示例如下:
- {"errcode":40013,"errmsg":"invalid appid"}
2.方法封装
笔者将查询分组的操作封装成getGroups()方法,该方法的实现如下:
- /**
- * 查询分组
- *
- * @param accessToken 调用接口凭证
- */
- @SuppressWarnings( { "unchecked", "deprecation" })
- public static List<WeixinGroup> getGroups(String accessToken) {
- List<WeixinGroup> weixinGroupList = null;
- // 拼接请求地址
- String requestUrl = "https://api.weixin.qq.com/cgi-bin/
- groups/get?access_token=ACCESS_TOKEN";
- requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken);
- // 查询分组
- JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
- if (null != jsonObject) {
- try {
- weixinGroupList = JSONArray.toList
- (jsonObject.getJSONArray("groups"), WeixinGroup.class);
- } catch (JSONException e) {
- weixinGroupList = null;
- int errorCode = jsonObject.getInt("errcode");
- String errorMsg = jsonObject.getString("errmsg");
- log.error("查询分组失败 errcode:{} errmsg:{}", errorCode, errorMsg);
- }
- }
- return weixinGroupList;
- }
getGroups()方法的返回值是一个WeixinGroup列表,WeixinGroup封装了获取查询分组接口返回的所有参数,该类的代码如下:
- package org.liufeng.course.pojo;
- /**
- * 公众账号分组信息
- *
- * @author liufeng
- * @date 2013-11-09
- */
- public class WeixinGroup {
- // 分组id
- private int id;
- // 分组名称
- private String name;
- // 分组内的用户数
- private int count;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getCount() {
- return count;
- }
- public void setCount(int count) {
- this.count = count;
- }
- }
3.案例:获取公众账号分组列表
下面是调用getGroups()方法获取公众账号分组列表的案例。
- public static void main(String args[]) {
- // 获取接口访问凭证
- String accessToken = CommonUtil.getToken("APPID", "APPSECRET").getAccessToken();
- // 获取分组列表
- List<WeixinGroup> groupList = getGroups(accessToken);
- // 循环输出各分组信息
- for (WeixinGroup group : groupList) {
- System.out.println(String.format("ID:%d 名称:%s 用户数:%d", group.getId(),
- group.getName(), group.getCount()));
- }
- }
笔者测试使用的公众账号没有新建分组,只有默认的3个分组:未分组、黑名单和星标组。因此,上述示例代码的运行结果如图6-10所示。
图6-10 查询分组示例的运行结果