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

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
package com.weixin.sendmessage;
 
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;
<br>//控制器
public class GetOpenIdAct {
 
    /**
     * 获取关注用户的所有openid
     * @return
     */
    @RequestMapping("/get_weixin_user.do")
    public String getWeixinUser(){
        String access_token=getToken();
        Set<String> openIds=getUsers(access_token);
        //openIds为所有关注用户的openid
 
        return null;
    }
 
 
    /**
     * 获取微信公众号关注用户
     * 官方接口文档: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="https://api.weixin.qq.com/cgi-bin/user/get";
        usersGetUrl+="?access_token="+access_token;
        JSONObject data=getUrlResponse(usersGetUrl);
        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){
                    JSONObject openIdData=(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 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";//微信提供获取access_token接口地址
        String appid = "";
        String secret = "";
 
        System.out.println("~~~~~appid:" + appid);
        System.out.println("~~~~~secret:" + secret);
        JSONObject tokenJson = new JSONObject();
        if (StringUtils.isNotBlank(appid) && StringUtils.isNotBlank(secret)) {
            tokenGetUrl += "&appid=" + appid + "&secret=" + secret;
            tokenJson = 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;
        }
    }
 
 
 
 
    private  Set<String> getUsers(Set<String>openIds,String url,String access_token,String next_openid) {
        JSONObject data=getUrlResponse(url);
        try {
            Integer count=(Integer) data.get("count");
            String nextOpenId=(String) data.get("next_openid");
            if(count>0){
                JSONObject openIdData=(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;
    }
 
    private 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;
        }
    }
 
    private 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;
        }
    }
 
 
    private 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;
            }
        }
 
    }
}

  

posted @   yvioo  阅读(2567)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示