JAVA微信公众号网页开发——获取公众号关注的所有用户(微信公众号粉丝)

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
 
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URI;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashSet;
import java.util.Set;

public class WeixinUtil {

	/*第三方用户唯一凭证*/
    private static final String APPID = "";
    /*第三方用户唯一凭证密钥,即appsecret*/
    private static final String SECRET = "";
    /*微信提供获取access_token接口地址*/
    private static final String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
    /*获取微信公众号关注用户接口地址*/
    private static final String get_userInfo_url = "https://api.weixin.qq.com/cgi-bin/user/get";

    public static void main(String[] args) {
        Set<String> openIds = new WeixinUtil().getUsers(new WeixinUtil().getToken());
        for (String s : openIds){
            System.out.println("openId:" +s);
        }
    }

/**
     * 获取微信公众号关注用户
     * 官方接口文档:https://developers.weixin.qq.com/doc/offiaccount/User_Management/Getting_a_User_List.html
     * @param access_token
     * @return
     */
    public Set<String> getUsers(String access_token) {
        String usersGetUrl=get_userInfo_url;
        usersGetUrl+="?access_token="+access_token;
        org.json.JSONObject data=new WeixinUtil ().getUrlResponse(usersGetUrl);
        System.out.println("~~~~~用户信息:" + data.toString());
        Set<String>openIds=new HashSet<String>();
        Integer total=0,count=0;
        try {
            total=(Integer) data.get("total");
            count=(Integer) data.get("count");
            //总关注用户数超过默认一万
            if(count<total){
                openIds.addAll(getUsers(openIds,usersGetUrl, access_token, (String)data.get("next_openid")));
            }else{
                //有关注者 json才有data参数
                if(count>0){
                    org.json.JSONObject openIdData=(org.json.JSONObject) data.get("data");
                    JSONArray openIdArray= (JSONArray) openIdData.get("openid");
                    for(int i=0;i<openIdArray.length();i++){
                        openIds.add((String) openIdArray.get(i));
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return openIds;
    }

    /**
     * 获取access_token
     * @return
     */
    public String getToken() {
        String tokenGetUrl = access_token_url;//微信提供获取access_token接口地址
        String appid = APPID;
        String secret = SECRET;

        System.out.println("~~~~~appid:" + appid);
        System.out.println("~~~~~secret:" + secret);
        org.json.JSONObject tokenJson = new org.json.JSONObject();
        if (StringUtils.isNotBlank(appid) && StringUtils.isNotBlank(secret)) {
            tokenGetUrl += "&appid=" + appid + "&secret=" + secret;
            tokenJson = new WeixinUtil ().getUrlResponse(tokenGetUrl);
            System.out.println("~~~~~tokenJson:" + tokenJson.toString());
            try {
                return (String) tokenJson.get("access_token");
            } catch (JSONException e) {
                System.out.println("报错了");
                return null;
            }
        } else {
            System.out.println("appid和secret为空");
            return null;
        }
    }

	/**
     * @描述 关注超过一万排序
     * @author dwl
     * @createTime 2022/2/21
     */
    private  Set<String> getUsers(Set<String>openIds,String url,String access_token,String next_openid) {
        org.json.JSONObject data=new GetOpenIdAct().getUrlResponse(url);
        try {
            Integer count=(Integer) data.get("count");
            String nextOpenId=(String) data.get("next_openid");
            if(count>0){
                org.json.JSONObject openIdData=(org.json.JSONObject) data.get("data");
                JSONArray openIdArray= (JSONArray) openIdData.get("openid");
                for(int i=0;i<openIdArray.length();i++){
                    openIds.add((String) openIdArray.get(i));
                }
            }
            if(StringUtils.isNotBlank(nextOpenId)){
                return getUsers(openIds,url, access_token, nextOpenId);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return openIds;
    }

	public JSONObject getUrlResponse(String url) {
        CharsetHandler handler = new CharsetHandler("UTF-8");
        try {
            HttpGet httpget = new HttpGet(new URI(url));
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            //HttpClient
            CloseableHttpClient client = httpClientBuilder.build();
            client = (CloseableHttpClient) wrapClient(client);
            return new JSONObject(client.execute(httpget, handler));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static HttpClient wrapClient(HttpClient base) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLSv1");
            X509TrustManager tm = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] xcs,
                                               String string) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] xcs,
                                               String string) throws CertificateException {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx, new String[]{"TLSv1"}, null,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            return httpclient;

        } catch (Exception ex) {
            return null;
        }
    }


    public class CharsetHandler implements ResponseHandler<String> {
        private String charset;

        public CharsetHandler(String charset) {
            this.charset = charset;
        }

        public String handleResponse(HttpResponse response)
                throws ClientProtocolException, IOException {
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(),
                        statusLine.getReasonPhrase());
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                if (!StringUtils.isBlank(charset)) {
                    return EntityUtils.toString(entity, charset);
                } else {
                    return EntityUtils.toString(entity);
                }
            } else {
                return null;
            }
        }

    }
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值