Java微信二次开发(八)

时间:2024-11-06 08:03:43

高级接口,先做了两个(获取用户信息和获取关注者列表)

第一步:找到包com.wtz.vo,新建类UserInfo.java

 package com.wtz.vo;

 /**
* @author wangtianze QQ:864620012
* @date 2017年4月24日 下午4:51:57
* <p>version:1.0</p>
* <p>description:微信用户的基本信息</p>
*/
public class UserInfo {
//用户的标识
private String openId;
//关注状态(1是关注,0是未关注),未关注时获取不到其余信息
private int subscribe;
//用户关注时间,为时间戳,如果用户曾多次关注,则取最后关注时间
private String subscribeTime;
//昵称
private String nickname;
//用户的性别(1是男性,2是女性,0是未知)
private int sex;
//用户所在国家
private String country;
//用户所在省份
private String province;
//用户所在城市
private String city;
//用户的语言,中文为zh_CN
private String language;
//用户头像
private String headImgUrl;
//unionid
private String unionid; public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public int getSubscribe() {
return subscribe;
}
public void setSubscribe(int subscribe) {
this.subscribe = subscribe;
}
public String getSubscribeTime() {
return subscribeTime;
}
public void setSubscribeTime(String subscribeTime) {
this.subscribeTime = subscribeTime;
}
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 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 getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getHeadImgUrl() {
return headImgUrl;
}
public void setHeadImgUrl(String headImgUrl) {
this.headImgUrl = headImgUrl;
}
public String getUnionid() {
return unionid;
}
public void setUnionid(String unionid) {
this.unionid = unionid;
}
}

第二步:找到包com.wtz.vo,新建类UserList.java

 package com.wtz.vo;

 import java.util.List;

 /**
* @author wangtianze QQ:864620012
* @date 2017年4月24日 下午5:08:28
* <p>version:1.0</p>
* <p>description:关注的用户列表</p>
*/
public class UserList {
//公众账号的总关注用户数
private int total;
//获取的openId个数
private int count;
//OpenID列表
private List<String> openIdList;
//拉取列表的后一个用户的OPENID
private String nextOpenId; public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public List<String> getOpenIdList() {
return openIdList;
}
public void setOpenIdList(List<String> openIdList) {
this.openIdList = openIdList;
}
public String getNextOpenId() {
return nextOpenId;
}
public void setNextOpenId(String nextOpenId) {
this.nextOpenId = nextOpenId;
}
}

第三步:找到包com.wtz.vo,新建类WeixinGroup.java

 package com.wtz.vo;

 /**
* @author wangtianze QQ:864620012
* @date 2017年4月24日 下午5:24:57
* <p>version:1.0</p>
* <p>description:公众账号分组信息</p>
*/
public class WeixinGroup {
//分组id
private int id;
//分组名称
private String name;
//分组内的用户数
private int count; public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}

第四步:找到包com.wtz.util,修改类WeixinUtil.java

 package com.wtz.util;

 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException; import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager; import net.sf.json.JSONObject; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.wtz.vo.Token; /**
* @author wangtianze QQ:864620012
* @date 2017年4月23日 下午5:08:02
* <p>version:1.0</p>
* <p>description:通用https请求工具类</p>
*/
public class WeixinUtil {
//需要导入库slf4j-api-1.5.10.jar和slf4j-log4j12-1.5.10.jar以及log4j-1.2.15.jar和log4j.properties
private static Logger log = LoggerFactory.getLogger(WeixinUtil.class); //凭证获取(GET)
public final static String token_url = "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){
//需要导入库json-lib-2.2.1-jdk15.jar
JSONObject jsonObject = null; //创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = {new MyX509TrustManager()};
try {
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 connection = (HttpsURLConnection)url.openConnection(); connection.setSSLSocketFactory(ssf); connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false); //设置请求方式(GET/POST)
connection.setRequestMethod(requestMethod); //当outputStr不为null时向输出流写入数据
if(null != outputStr){
OutputStream outputStream = connection.getOutputStream();
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
} //从输入流读取返回内容
InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
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;
connection.disconnect(); jsonObject = JSONObject.fromObject(buffer.toString()); } catch (ConnectException e) {
log.error("连接超时:{}",e);
} catch (NoSuchAlgorithmException e) {
log.error("https请求异常:{}",e);
} catch (NoSuchProviderException e) {
log.error("https请求异常:{}",e);
} catch (KeyManagementException e) {
log.error("https请求异常:{}",e);
} catch (MalformedURLException e) {
log.error("https请求异常:{}",e);
} catch (IOException e){
log.error("https请求异常:{}",e);
} catch (Exception e) {
log.error("https请求异常:{}",e);
} return jsonObject;
} /**
* 获取接口访问凭证
*
* @param appid
* @param appsecret 密钥
* @return
*/
public static Token getToken(String appid,String appsecret){
Token token = null;
String requestUrl = token_url.replace("APPID", appid).replace("APPSecret", appsecret); //发起GET请求获取凭证
JSONObject jsonObject = httpsRequest(requestUrl,"GET",null); if(null != jsonObject){
token = new Token();
token.setAccessToken(jsonObject.getString("access_token"));
token.setExpiresIn(jsonObject.getInt("expires_in"));
} 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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
} /**
* 根据内容类型判断来返回文件的扩展名
* @param contentType 内容类型
* @return
*/
public static String getFileExt(String contentType){
String fileExt = "";
if("img/jepg".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;
}
}

第五步:找到包com.wtz.util,新建类AdvancedUtil.java

 package com.wtz.util;

 import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List; import net.sf.json.JSONArray;
import net.sf.json.JSONObject; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.wtz.vo.UserInfo;
import com.wtz.vo.UserList;
import com.wtz.vo.WeixinGroup; /**
* @author wangtianze QQ:864620012
* @date 2017年4月24日 下午7:36:03
* <p>version:1.0</p>
* <p>description:高级接口工具类</p>
*/
public class AdvancedUtil {
private static Logger log = LoggerFactory.getLogger(AdvancedUtil.class); /**
* 获取用户信息
*
* @param accessToken 接口访问凭证
* @param openId 用户凭证
* @return WeixinUserInfo
*/
public static UserInfo getUserInfo(String accessToken,String openId){
UserInfo 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);
//获取用户信息
JSONObject jsonObject = WeixinUtil.httpsRequest(requestUrl, "GET", null); if(null != jsonObject){
try{
weixinUserInfo = new UserInfo(); //用户的标识
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")); //uninonid
weixinUserInfo.setUnionid(jsonObject.getString("unionid"));
}catch(Exception e){
if(0 == weixinUserInfo.getSubscribe()){
log.error("用户{}已取消关注",weixinUserInfo.getOpenId());
}else{
int errorCode = jsonObject.getInt("errcode");
String errorMsg = jsonObject.getString("errmsg");
log.error("获取用户信息失败 errorcode:{} errormsg:{}",errorCode,errorMsg);
}
}
}
return weixinUserInfo;
} /**
* 获取关注者列表
*
* @param accessToken 调用接口凭证
* @param nextOpenId 第一个拉取nextOpenId,不填默认从头开始拉取
* @return WeixinUserList
*/
@SuppressWarnings({ "deprecation", "unchecked" })
public static UserList getUserList(String accessToken,String nextOpenId){
UserList weixinUserList = null;
if(null == nextOpenId){
nextOpenId = "";
}
//拼接请求地址
String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID"; requestUrl.replace("ACCESS_TOKEN", accessToken).replace("NEXT_OPENID",nextOpenId); //获取关注者列表
JSONObject jsonObject = WeixinUtil.httpsRequest(requestUrl, "GET", null); //如果请求成功
if(null != jsonObject){
weixinUserList = new UserList();
weixinUserList.setTotal(jsonObject.getInt("total"));
weixinUserList.setCount(jsonObject.getInt("count"));
weixinUserList.setNextOpenId(jsonObject.getString("next_openid"));
JSONObject dataObject = (JSONObject)jsonObject.get("data");
weixinUserList.setOpenIdList(JSONArray.toList(dataObject.getJSONArray("openid"),List.class));
} return weixinUserList;
} public static void main(String[] args){
//获取接口访问凭证
String accessToken = WeixinUtil.getToken(Parameter.appId,Parameter.appSecret).getAccessToken();
System.out.println("accessToken:" + accessToken); //获取关注者列表
UserList weixinUserList = getUserList(accessToken,"");
System.out.println("总关注用户数:" + weixinUserList.getTotal());
System.out.println("本次获取用户数:" + weixinUserList.getCount());
System.out.println("OpenId列表:" + weixinUserList.getOpenIdList().toString());
System.out.println("next_openid" + weixinUserList.getNextOpenId()); UserInfo user = null;
List<String> list = weixinUserList.getOpenIdList();
for(int i = 0; i < list.size(); i++){
//获取用户信息
user = getUserInfo(accessToken,(String)list.get(i));
System.out.println("OpenId:" + user.getOpenId());
System.out.println("关注状态:" + user.getSubscribe());
System.out.println("关注时间:" + (new SimpleDateFormat("yyyy-MM-dd HH:mm-ss").format(new Date(new Long(user.getSubscribeTime())))));
System.out.println("昵称:" + user.getNickname());
System.out.println("性别:" + user.getSex());
System.out.println("国家:" + user.getCountry());
System.out.println("省份:" + user.getProvince());
System.out.println("城市:" + user.getCity());
System.out.println("语言:" + user.getLanguage());
System.out.println("头像:" + user.getHeadImgUrl());
System.out.println("unionid:" + user.getUnionid());
System.out.println("=====================================");
}
}
}

高级接口(获取用户信息和获取关注者列表)完成