获取微信公众号用户关注列表
通用工具类:CommonUtil
package com.weixin.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import com.weixin.entity.AccessToken;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 通用工具
*/
public class CommonUtil {
private static Logger log = LoggerFactory.getLogger(CommonUtil.class);
// 凭证获取Access_Token(请求方式为GET)
public final static String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
/**
* 发送https请求
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
// 当outputStr不为null时向输出流写数据
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 设置编码格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
log.error("连接超时:{}", ce);
} catch (Exception e) {
log.error("https请求异常:{}", e);
}
return jsonObject;
}
/**
* 获取接口访问凭证
*
* @param appid 凭证
* @param appsecret 密钥
* @return
*/
public static AccessToken getToken(String appid, String appsecret) {
AccessToken token = null;
String requestUrl = tokenUrl.replace("APPID", appid).replace("APPSECRET", appsecret);
// 发起GET请求获取凭证
JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
if (null != jsonObject) {
try {
token = new AccessToken();
token.setAccessToken(jsonObject.getString("access_token"));
token.setExpiresIn(jsonObject.getInt("expires_in"));
} catch (JSONException e) {
token = null;
// 获取token失败
log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
return token;
}
/**
* URL编码(utf-8)
*
* @param source
* @return
*/
public static String urlEncodeUTF8(String source) {
String result = source;
try {
result = java.net.URLEncoder.encode(source, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
/**
* 根据内容类型判断文件扩展名
*
* @param contentType 内容类型
* @return
*/
public static String getFileExt(String contentType) {
String fileExt = "";
if ("image/jpeg".equals(contentType))
fileExt = ".jpg";
else if ("audio/mpeg".equals(contentType))
fileExt = ".mp3";
else if ("audio/amr".equals(contentType))
fileExt = ".amr";
else if ("video/mp4".equals(contentType))
fileExt = ".mp4";
else if ("video/mpeg4".equals(contentType))
fileExt = ".mp4";
return fileExt;
}
}
获取用户关注列表信息:WeiXinUtils
package com.weixin.util;
import com.weixin.entity.WeixinUser;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
public class WeiXinUtils {
private static Logger log = LoggerFactory.getLogger(CommonUtil.class);
/**
* 获取用户信息
*
* @param accessToken 接口访问凭证
* @param openId 用户标识
* @return WeixinUserInfo
*/
public static WeixinUser getUserInfo(String accessToken, String openId) {
WeixinUser weixinUserInfo = null;
// 拼接请求地址
//String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID";
// requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openId;
// 获取用户信息
JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
//System.out.println("jsonObject: "+jsonObject);
if (null != jsonObject) {
try {
weixinUserInfo = new WeixinUser();
// 用户的标识
weixinUserInfo.setOpenid(jsonObject.getString("openid"));
// 关注状态(1是关注,0是未关注),未关注时获取不到其余信息
weixinUserInfo.setSubscribe(jsonObject.getInt("subscribe"));
// 用户关注时间
weixinUserInfo.setSubscribeTime(jsonObject.getString("subscribe_time"));
// 昵称
weixinUserInfo.setNickname(jsonObject.getString("nickname"));
// 用户的性别(1是男性,2是女性,0是未知)
weixinUserInfo.setSex(jsonObject.getInt("sex"));
// 用户所在国家
weixinUserInfo.setCountry(jsonObject.getString("country"));
// 用户所在省份
weixinUserInfo.setProvince(jsonObject.getString("province"));
// 用户所在城市
weixinUserInfo.setCity(jsonObject.getString("city"));
// 用户的语言,简体中文为zh_CN
weixinUserInfo.setLanguage(jsonObject.getString("language"));
// 用户头像
weixinUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
} catch (Exception e) {
if (0 == weixinUserInfo.getSubscribe()) {
log.error("用户{}已取消关注", weixinUserInfo.getOpenid());
// System.out.println("用户{}已取消关注"+weixinUserInfo.getOpenid());
} else {
int errorCode = jsonObject.getInt("errcode");
String errorMsg = jsonObject.getString("errmsg");
log.error("获取用户信息失败 errcode:{} errmsg:{}", errorCode, errorMsg);
//System.out.println("获取用户信息失败 errcode:{} errmsg:{}"+errorCode+errorMsg);
}
}
}
return weixinUserInfo;
}
/**
* 通过accessToken 和 openIdList 获取多个用户关注列表信息
* @param accessToken 接口访问凭证
* @param openIdList 用户标识
* @return 用户关注列表信息 返回类型为list
*/
public List<WeixinUser> getUserInfoList(String accessToken, List<String> openIdList){
List<WeixinUser> weixinUserList = new ArrayList<>();
WeixinUser user=null;
for(String openId : openIdList) {
user = new WeixinUser();
user =getUserInfo(accessToken,openId);
weixinUserList.add(user);
}
return weixinUserList;
}
}
实体类:
package com.weixin.entity;
public class AccessToken {
// 接口访问凭证
private String accessToken;
// 凭证有效期,单位:秒
private int expiresIn;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
}
package com.weixin.entity;
public class WeixinUser {
private int subscribe;// 用户是否订阅该公众号标识,值为0时,代表此用户没有关注该公众号,拉取不到其余信息。
private String openid;// 用户的标识,对当前公众号唯一
private String nickname;// 用户的昵称
private int sex;// 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
private String city;// 用户所在城市
private String country;// 用户所在国家
private String province;// 用户所在省份
private String language;// 用户的语言,简体中文为zh_CN
private String subscribeTime;// 用户关注的时间
private String headImgUrl; // 用户头像
public int getSubscribe() {
return subscribe;
}
public void setSubscribe(int subscribe) {
this.subscribe = subscribe;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getSubscribeTime() {
return subscribeTime;
}
public void setSubscribeTime(String subscribeTime) {
this.subscribeTime = subscribeTime;
}
public String getHeadImgUrl() {
return headImgUrl;
}
public void setHeadImgUrl(String headImgUrl) {
this.headImgUrl = headImgUrl;
}
@Override
public String toString() {
return "WeixinUser{" +
"subscribe=" + subscribe +
", openid='" + openid + '\'' +
", nickname='" + nickname + '\'' +
", sex=" + sex +
", city='" + city + '\'' +
", country='" + country + '\'' +
", province='" + province + '\'' +
", language='" + language + '\'' +
", subscribeTime='" + subscribeTime + '\'' +
", headImgUrl='" + headImgUrl + '\'' +
'}';
}
}
获取OpenId
package com.weixin.util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class GetOpenIdUtil {
public List<String> getOpenIdList(String appid,String appsecret,String next_openId){
//获取接口访问凭证
String accessToken = CommonUtil.getToken(appid, appsecret).getAccessToken();
String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token="+accessToken+"&next_openid="+next_openId;
JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
String data = jsonObject.getString("data");
JSONObject json = JSONObject.fromObject(data);
List<String> listOpenId = new ArrayList<String>();
if (jsonObject.has("data")) {
JSONArray list = json.getJSONArray("openid");
for (int i = 0; i < list.size(); i++) {
listOpenId.add(list.getString(i));
}
}
return listOpenId;
}
}
微信请求–信息管理器
package com.weixin.util;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
/**
* 微信请求--信息管理器
*/
public class MyX509TrustManager implements X509TrustManager {
public MyX509TrustManager() {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
测试
@Test
public void test1(){
GetOpenIdUtil getOpenIdList = new GetOpenIdUtil();
List<String> openIdList = getOpenIdList.getOpenIdList("wx8dbd76c49615fac9","2ce38ac5f549e4984ecaa67934edd081","");
WeiXinUtils weiXinUtils2 = new WeiXinUtils();
String accessToken = CommonUtil.getToken("wx8dbd76c49615fac9", "2ce38ac5f549e4984ecaa67934edd081").getAccessToken();
List<WeixinUser> list = weiXinUtils2.getUserInfoList(accessToken,openIdList);
for (int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
}

3万+

被折叠的 条评论
为什么被折叠?



