Java微信二次开发(八)

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

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

 1 package com.wtz.vo;
 2 
 3 /**
 4  *     @author wangtianze QQ:864620012
 5  *    @date 2017年4月24日 下午4:51:57
 6  *  <p>version:1.0</p>
 7  *     <p>description:微信用户的基本信息</p>
 8  */
 9 public class UserInfo {
10     //用户的标识
11     private String openId;
12     //关注状态(1是关注,0是未关注),未关注时获取不到其余信息
13     private int subscribe;
14     //用户关注时间,为时间戳,如果用户曾多次关注,则取最后关注时间
15     private String subscribeTime;
16     //昵称
17     private String nickname;
18     //用户的性别(1是男性,2是女性,0是未知)
19     private int sex;
20     //用户所在国家
21     private String country;
22     //用户所在省份
23     private String province;
24     //用户所在城市
25     private String city;
26     //用户的语言,中文为zh_CN
27     private String language;
28     //用户头像
29     private String headImgUrl;
30     //unionid
31     private String unionid;
32     
33     public String getOpenId() {
34         return openId;
35     }
36     public void setOpenId(String openId) {
37         this.openId = openId;
38     }
39     public int getSubscribe() {
40         return subscribe;
41     }
42     public void setSubscribe(int subscribe) {
43         this.subscribe = subscribe;
44     }
45     public String getSubscribeTime() {
46         return subscribeTime;
47     }
48     public void setSubscribeTime(String subscribeTime) {
49         this.subscribeTime = subscribeTime;
50     }
51     public String getNickname() {
52         return nickname;
53     }
54     public void setNickname(String nickname) {
55         this.nickname = nickname;
56     }
57     public int getSex() {
58         return sex;
59     }
60     public void setSex(int sex) {
61         this.sex = sex;
62     }
63     public String getCountry() {
64         return country;
65     }
66     public void setCountry(String country) {
67         this.country = country;
68     }
69     public String getProvince() {
70         return province;
71     }
72     public void setProvince(String province) {
73         this.province = province;
74     }
75     public String getCity() {
76         return city;
77     }
78     public void setCity(String city) {
79         this.city = city;
80     }
81     public String getLanguage() {
82         return language;
83     }
84     public void setLanguage(String language) {
85         this.language = language;
86     }
87     public String getHeadImgUrl() {
88         return headImgUrl;
89     }
90     public void setHeadImgUrl(String headImgUrl) {
91         this.headImgUrl = headImgUrl;
92     }
93     public String getUnionid() {
94         return unionid;
95     }
96     public void setUnionid(String unionid) {
97         this.unionid = unionid;
98     }
99 }

 

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

 1 package com.wtz.vo;
 2 
 3 import java.util.List;
 4 
 5 /**
 6  *     @author wangtianze QQ:864620012
 7  *    @date 2017年4月24日 下午5:08:28
 8  *  <p>version:1.0</p>
 9  *     <p>description:关注的用户列表</p>
10  */
11 public class UserList {
12     //公众账号的总关注用户数
13     private int total;
14     //获取的openId个数
15     private int count;
16     //OpenID列表
17     private List<String> openIdList;
18     //拉取列表的后一个用户的OPENID
19     private String nextOpenId;
20     
21     public int getTotal() {
22         return total;
23     }
24     public void setTotal(int total) {
25         this.total = total;
26     }
27     public int getCount() {
28         return count;
29     }
30     public void setCount(int count) {
31         this.count = count;
32     }
33     public List<String> getOpenIdList() {
34         return openIdList;
35     }
36     public void setOpenIdList(List<String> openIdList) {
37         this.openIdList = openIdList;
38     }
39     public String getNextOpenId() {
40         return nextOpenId;
41     }
42     public void setNextOpenId(String nextOpenId) {
43         this.nextOpenId = nextOpenId;
44     }
45 }

 

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

 1 package com.wtz.vo;
 2 
 3 /**
 4  *     @author wangtianze QQ:864620012
 5  *    @date 2017年4月24日 下午5:24:57
 6  *  <p>version:1.0</p>
 7  *     <p>description:公众账号分组信息</p>
 8  */
 9 public class WeixinGroup {
10     //分组id
11     private int id;
12     //分组名称
13     private String name;
14     //分组内的用户数
15     private int count;
16     
17     public int getId() {
18         return id;
19     }
20     public void setId(int id) {
21         this.id = id;
22     }
23     public String getName() {
24         return name;
25     }
26     public void setName(String name) {
27         this.name = name;
28     }
29     public int getCount() {
30         return count;
31     }
32     public void setCount(int count) {
33         this.count = count;
34     }
35 }

 

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

  1 package com.wtz.util;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.IOException;
  5 import java.io.InputStream;
  6 import java.io.InputStreamReader;
  7 import java.io.OutputStream;
  8 import java.io.UnsupportedEncodingException;
  9 import java.net.ConnectException;
 10 import java.net.MalformedURLException;
 11 import java.net.URL;
 12 import java.security.KeyManagementException;
 13 import java.security.NoSuchAlgorithmException;
 14 import java.security.NoSuchProviderException;
 15 
 16 import javax.net.ssl.HttpsURLConnection;
 17 import javax.net.ssl.SSLContext;
 18 import javax.net.ssl.SSLSocketFactory;
 19 import javax.net.ssl.TrustManager;
 20 
 21 import net.sf.json.JSONObject;
 22 
 23 import org.slf4j.Logger;
 24 import org.slf4j.LoggerFactory;
 25 
 26 import com.wtz.vo.Token;
 27 
 28 /**
 29  *     @author wangtianze QQ:864620012
 30  *    @date 2017年4月23日 下午5:08:02
 31  *  <p>version:1.0</p>
 32  *     <p>description:通用https请求工具类</p>
 33  */
 34 public class WeixinUtil {
 35     //需要导入库slf4j-api-1.5.10.jar和slf4j-log4j12-1.5.10.jar以及log4j-1.2.15.jar和log4j.properties
 36     private static Logger log = LoggerFactory.getLogger(WeixinUtil.class);
 37     
 38     //凭证获取(GET)
 39     public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
 40     
 41     /**
 42      * 发送https请求
 43      * 
 44      * @param requestUrl 请求地址
 45      * @param requestMethod 请求方式(GET/POST)
 46      * @param outputStr 提交的数据
 47      * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
 48      */
 49     public static JSONObject httpsRequest(String requestUrl,String requestMethod,String outputStr){
 50         //需要导入库json-lib-2.2.1-jdk15.jar
 51         JSONObject jsonObject = null;
 52         
 53         //创建SSLContext对象,并使用我们指定的信任管理器初始化
 54         TrustManager[] tm = {new MyX509TrustManager()};
 55         try {
 56             SSLContext sslContext = SSLContext.getInstance("SSL","SunJSSE");
 57             
 58             sslContext.init(null, tm, new java.security.SecureRandom());
 59             
 60             //从上述SSLContext对象中得到SSLSocketFactory对象
 61             SSLSocketFactory ssf = sslContext.getSocketFactory();
 62             
 63             URL url = new URL(requestUrl);
 64             
 65             HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
 66             
 67             connection.setSSLSocketFactory(ssf);
 68             
 69             connection.setDoOutput(true);
 70             connection.setDoInput(true);
 71             connection.setUseCaches(false);
 72             
 73             //设置请求方式(GET/POST)
 74             connection.setRequestMethod(requestMethod);
 75             
 76             //当outputStr不为null时向输出流写入数据
 77             if(null != outputStr){
 78                 OutputStream outputStream = connection.getOutputStream();
 79                 outputStream.write(outputStr.getBytes("UTF-8"));
 80                 outputStream.close();
 81             }
 82             
 83             //从输入流读取返回内容
 84             InputStream inputStream = connection.getInputStream();
 85             InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
 86             BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
 87             String str = null;
 88             StringBuffer buffer = new StringBuffer();
 89             while((str = bufferedReader.readLine()) != null){
 90                 buffer.append(str);
 91             }
 92             
 93             //释放资源
 94             bufferedReader.close();
 95             inputStreamReader.close();
 96             inputStream.close();
 97             inputStream = null;
 98             connection.disconnect();
 99             
100             jsonObject = JSONObject.fromObject(buffer.toString());
101             
102         } catch (ConnectException e) {
103             log.error("连接超时:{}",e);
104         } catch (NoSuchAlgorithmException e) {
105             log.error("https请求异常:{}",e);
106         } catch (NoSuchProviderException e) {
107             log.error("https请求异常:{}",e);
108         } catch (KeyManagementException e) {
109             log.error("https请求异常:{}",e);
110         } catch (MalformedURLException e) {
111             log.error("https请求异常:{}",e);
112         } catch (IOException e){
113             log.error("https请求异常:{}",e);
114         } catch (Exception e) {
115             log.error("https请求异常:{}",e);
116         }
117     
118         return jsonObject;
119     }
120     
121     /**
122      * 获取接口访问凭证
123      * 
124      * @param appid 
125      * @param appsecret 密钥
126      * @return
127      */
128     public static Token getToken(String appid,String appsecret){
129         Token token = null;
130         String requestUrl = token_url.replace("APPID", appid).replace("APPSecret", appsecret);
131         
132         //发起GET请求获取凭证
133         JSONObject jsonObject = httpsRequest(requestUrl,"GET",null);
134         
135         if(null != jsonObject){
136             token = new Token();
137             token.setAccessToken(jsonObject.getString("access_token"));
138             token.setExpiresIn(jsonObject.getInt("expires_in"));
139         }
140         
141         return token;
142     }
143     
144     /**
145      * URL编码(utf-8)
146      * @param source
147      * @return
148      */
149     public static String urlEncodeUTF8(String source){
150         String result = source;
151         try {
152             result = java.net.URLEncoder.encode(source,"utf-8");
153         } catch (UnsupportedEncodingException e) {
154             // TODO Auto-generated catch block
155             e.printStackTrace();
156         }
157         return result;
158     }
159     
160     /**
161      * 根据内容类型判断来返回文件的扩展名
162      * @param contentType 内容类型
163      * @return
164      */
165     public static String getFileExt(String contentType){
166         String fileExt = "";
167         if("img/jepg".equals(contentType)){
168             fileExt = ".jpg";
169         }else if("audio/mpeg".equals(contentType)){
170             fileExt = ".mp3";
171         }else if("audio/amr".equals(contentType)){
172             fileExt = ".amr";
173         }else if("video/mp4".equals(contentType)){
174             fileExt = ".mp4";
175         }else if("video/mpeg4".equals(contentType)){
176             fileExt = ".mp4";
177         }
178         
179         return fileExt;
180     }
181 }

 

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

  1 package com.wtz.util;
  2 
  3 import java.text.SimpleDateFormat;
  4 import java.util.Date;
  5 import java.util.List;
  6 
  7 import net.sf.json.JSONArray;
  8 import net.sf.json.JSONObject;
  9 
 10 import org.slf4j.Logger;
 11 import org.slf4j.LoggerFactory;
 12 
 13 import com.wtz.vo.UserInfo;
 14 import com.wtz.vo.UserList;
 15 import com.wtz.vo.WeixinGroup;
 16 
 17 /**
 18  *     @author wangtianze QQ:864620012
 19  *    @date 2017年4月24日 下午7:36:03
 20  *  <p>version:1.0</p>
 21  *     <p>description:高级接口工具类</p>
 22  */
 23 public class AdvancedUtil {
 24     private static Logger log = LoggerFactory.getLogger(AdvancedUtil.class);
 25     
 26     /**
 27      * 获取用户信息
 28      * 
 29      * @param accessToken 接口访问凭证
 30      * @param openId 用户凭证
 31      * @return WeixinUserInfo
 32      */
 33     public static UserInfo getUserInfo(String accessToken,String openId){
 34         UserInfo weixinUserInfo = null;
 35         //拼接请求地址
 36         String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID";
 37         requestUrl = requestUrl.replace("ACCESS_TOKEN",accessToken).replace("OPENID",openId);
 38         //获取用户信息
 39         JSONObject jsonObject = WeixinUtil.httpsRequest(requestUrl, "GET", null);
 40         
 41         if(null != jsonObject){
 42             try{
 43                 weixinUserInfo = new UserInfo();
 44                 
 45                 //用户的标识
 46                 weixinUserInfo.setOpenId(jsonObject.getString("openid"));
 47                 
 48                 //关注状态(1是关注,0是未关注),未关注时获取不到其余信息
 49                 weixinUserInfo.setSubscribe(jsonObject.getInt("subscribe"));
 50                 
 51                 //用户关注时间
 52                 weixinUserInfo.setSubscribeTime(jsonObject.getString("subscribe_time"));
 53                 
 54                 //昵称
 55                 weixinUserInfo.setNickname(jsonObject.getString("nickname"));
 56                 
 57                 //用户的性别(1是男性,2是女性,0是未知)
 58                 weixinUserInfo.setSex(jsonObject.getInt("sex"));
 59                 
 60                 //用户所在的国家
 61                 weixinUserInfo.setCountry(jsonObject.getString("country"));
 62                 
 63                 //用户所在的省份
 64                 weixinUserInfo.setProvince(jsonObject.getString("province"));
 65                 
 66                 //用户所在的城市
 67                 weixinUserInfo.setCity(jsonObject.getString("city"));
 68                 
 69                 //用户的语言,简体中文为zh_CN
 70                 weixinUserInfo.setLanguage(jsonObject.getString("language"));
 71                 
 72                 //用户头像
 73                 weixinUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
 74                 
 75                 //uninonid
 76                 weixinUserInfo.setUnionid(jsonObject.getString("unionid"));
 77             }catch(Exception e){
 78                 if(0 == weixinUserInfo.getSubscribe()){
 79                     log.error("用户{}已取消关注",weixinUserInfo.getOpenId());
 80                 }else{
 81                     int errorCode = jsonObject.getInt("errcode");
 82                     String errorMsg = jsonObject.getString("errmsg");
 83                     log.error("获取用户信息失败 errorcode:{} errormsg:{}",errorCode,errorMsg);
 84                 }
 85             }
 86         }
 87         return weixinUserInfo;
 88     } 
 89     
 90     /**
 91      * 获取关注者列表
 92      * 
 93      * @param accessToken 调用接口凭证
 94      * @param nextOpenId 第一个拉取nextOpenId,不填默认从头开始拉取
 95      * @return WeixinUserList
 96      */
 97     @SuppressWarnings({ "deprecation", "unchecked" })
 98     public static UserList getUserList(String accessToken,String nextOpenId){
 99         UserList weixinUserList = null;
100         if(null == nextOpenId){
101             nextOpenId = "";
102         }
103         //拼接请求地址
104         String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID";
105         
106         requestUrl.replace("ACCESS_TOKEN", accessToken).replace("NEXT_OPENID",nextOpenId);
107         
108         //获取关注者列表
109         JSONObject jsonObject = WeixinUtil.httpsRequest(requestUrl, "GET", null);
110         
111         //如果请求成功
112         if(null != jsonObject){
113             weixinUserList = new UserList();
114             weixinUserList.setTotal(jsonObject.getInt("total"));
115             weixinUserList.setCount(jsonObject.getInt("count"));
116             weixinUserList.setNextOpenId(jsonObject.getString("next_openid"));
117             JSONObject dataObject = (JSONObject)jsonObject.get("data");
118             weixinUserList.setOpenIdList(JSONArray.toList(dataObject.getJSONArray("openid"),List.class));    
119         }
120 
121         return weixinUserList;
122     }
123     
124     public static void main(String[] args){
125         //获取接口访问凭证
126         String accessToken = WeixinUtil.getToken(Parameter.appId,Parameter.appSecret).getAccessToken();
127         System.out.println("accessToken:" + accessToken);
128         
129         //获取关注者列表
130         UserList weixinUserList = getUserList(accessToken,"");
131         System.out.println("总关注用户数:" + weixinUserList.getTotal());
132         System.out.println("本次获取用户数:" + weixinUserList.getCount());
133         System.out.println("OpenId列表:" + weixinUserList.getOpenIdList().toString());
134         System.out.println("next_openid" + weixinUserList.getNextOpenId());
135         
136         UserInfo user = null;
137         List<String> list = weixinUserList.getOpenIdList();
138         for(int i = 0; i < list.size(); i++){
139             //获取用户信息
140             user = getUserInfo(accessToken,(String)list.get(i));
141             System.out.println("OpenId:" + user.getOpenId());
142             System.out.println("关注状态:" + user.getSubscribe());
143             System.out.println("关注时间:" + (new SimpleDateFormat("yyyy-MM-dd HH:mm-ss").format(new Date(new Long(user.getSubscribeTime())))));
144             System.out.println("昵称:" + user.getNickname());
145             System.out.println("性别:" + user.getSex());
146             System.out.println("国家:" + user.getCountry());
147             System.out.println("省份:" + user.getProvince());
148             System.out.println("城市:" + user.getCity());
149             System.out.println("语言:" + user.getLanguage());
150             System.out.println("头像:" + user.getHeadImgUrl());
151             System.out.println("unionid:" + user.getUnionid());
152             System.out.println("=====================================");
153         }
154     }
155 }

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

posted on 2017-04-25 10:18  wangtianze  阅读(492)  评论(0编辑  收藏  举报

导航