JAVA递归实现[微信获取全部粉丝列表]

场景,获取微信服务号/订阅号粉丝列表,微信提供API每次最多返回10000条;要想获取全部粉丝列表,需要手动的调用N次实现;

解决方案:递归调用,获取全部粉丝列表

直接上代码:
获取全部粉丝列表调用:

    // 递归获取全部粉丝列表
    public void getAll(){

        long start = System.currentTimeMillis();
        // 获取订阅号token
        String sub_token = fetchToken(SUB_APP_ID, SUB_APP_SECRET);
        getUserList(sub_token,"");
        long end = System.currentTimeMillis()-start;
        logger.info("执行时间:"+end+"ms");

    }

getUserList方法:

// 递归调用next_openid
    private void getUserList(String sub_token, String next_openid) {

        HttpMethod method = null;
        String res = null;
        String GetUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token="+sub_token+"&next_openid="+next_openid; // +"&next_openid=o_GmSwimbNwkk9ca9ogsRCClzeUg"
        method = new GetMethod(GetUrl);
        try {
            res = HttpClientUtil.httpRequest(method);
            if (!"none".equals(res)) {
                JSONObject jsonobj = JSON.parseObject(res);
                String nextOpen = jsonobj.getString("next_openid");
                logger.info("start——next_openid:" + nextOpen);
                JSONObject jo = (JSONObject) jsonobj.get("data");
                JSONArray jsonArray = JSON.parseArray(jo.getString("openid"));
                if (null != jo && null != jsonArray) {
                    // 获取服务号token
                    logger.info("========================================================================");
                    StringBuffer sb = new StringBuffer();
                    sb.append("INSERT INTO `wx_sub` VALUES ");
                    for (int i = 0; i < jsonArray.size(); i++) {
                        String openId = (String) jsonArray.get(i);
                        if(i==jsonArray.size()-1){
                            sb.append("(UUID(),'"+openId+"','"+i+"',now());");
                        }else {
                            sb.append("(UUID(),'"+openId+"','"+i+"',now()),");
                        }
                        // 通过openId获取unionId
//                        getUserInfo(sub_token,openId);
                    }
                    logger.info(sb);
                    logger.info("========================================================================");
                }
                logger.info("end——next_openid:" + nextOpen);
                // 继续获取
                if(StringUtils.isNotEmpty(nextOpen)){
                    getUserList(sub_token,nextOpen);
                }
            }
        } catch (IOException e) {
            System.out.print("IOException");
        } catch (Exception e) {
            System.out.print("Exception");
        }
    }

获取token方法:token有效期-2个小时

/**
     * @Title: fetchToken
     * @Description: 获取微信的token
     * @return   返回结果JSONOjbect对象:{"access_token":"","expires_in":7200}
     */
    protected String fetchToken(String appid,String appscret) {

        String access_token = "";
        // 获取AccessToken
        String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"
            + "&appid=" + appid + "&secret=" + appscret;
        HttpMethod method = new GetMethod(token_url);
        String res = null;
        try {
            res = HttpClientUtil.httpRequest(method);
            if (!"none".equals(res)) {
                JSONObject jsonobj = JSON.parseObject(res);
                access_token = jsonobj.getString("access_token");
            }
        } catch (IOException e) {
            return access_token;
        } catch (Exception e) {
            return access_token;
        }

        return access_token;
    }

通过openId获取用户信息接口:

// 根据token,openId获取用户信息
    public void getUserInfo(String sub_token, String openId){
        String UserInfoUrl = "https://api.weixin.qq.com/cgi-bin/user/info" + "?access_token="+ sub_token + "&openid="+ openId + "&lang=zh_CN";
        HttpMethod mh = new GetMethod(UserInfoUrl);
        String resInfo = null;
        try {
            resInfo = HttpClientUtil.httpRequest(mh);
            if(!"none".equals(resInfo)){
                JSONObject j = JSON.parseObject(resInfo);
                WxSub wxSub = new WxSub();
                wxSub.setId(UUID.randomUUID().toString());
                wxSub.setOpenid(openId);
                wxSub.setCreatedat(new Date());
                String unionId = j.getString("unionid");
                String username = j.getString("nickname");
                wxSub.setUnionid(unionId);
                templateTool.save(wxSub);
                System.out.println("unionId:"+unionId);
                System.out.println("openId:"+openId);
                System.out.println("username:"+username);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

你可能感兴趣的:(JAVA递归实现[微信获取全部粉丝列表])