首页 技术 正文
技术 2022年11月15日
0 收藏 876 点赞 4,838 浏览 5166 个字
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;

//控制器
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;
}
} }
}

  

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,964
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,486
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,331
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,114
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,747
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,781