Java微信二次开发(八)
生活随笔
收集整理的這篇文章主要介紹了
Java微信二次开发(八)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
高級(jí)接口,先做了兩個(gè)(獲取用戶(hù)信息和獲取關(guān)注者列表)
第一步:找到包c(diǎn)om.wtz.vo,新建類(lèi)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:微信用戶(hù)的基本信息</p> 8 */ 9 public class UserInfo { 10 //用戶(hù)的標(biāo)識(shí) 11 private String openId; 12 //關(guān)注狀態(tài)(1是關(guān)注,0是未關(guān)注),未關(guān)注時(shí)獲取不到其余信息 13 private int subscribe; 14 //用戶(hù)關(guān)注時(shí)間,為時(shí)間戳,如果用戶(hù)曾多次關(guān)注,則取最后關(guān)注時(shí)間 15 private String subscribeTime; 16 //昵稱(chēng) 17 private String nickname; 18 //用戶(hù)的性別(1是男性,2是女性,0是未知) 19 private int sex; 20 //用戶(hù)所在國(guó)家 21 private String country; 22 //用戶(hù)所在省份 23 private String province; 24 //用戶(hù)所在城市 25 private String city; 26 //用戶(hù)的語(yǔ)言,中文為zh_CN 27 private String language; 28 //用戶(hù)頭像 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 }?
第二步:找到包c(diǎn)om.wtz.vo,新建類(lèi)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:關(guān)注的用戶(hù)列表</p> 10 */ 11 public class UserList { 12 //公眾賬號(hào)的總關(guān)注用戶(hù)數(shù) 13 private int total; 14 //獲取的openId個(gè)數(shù) 15 private int count; 16 //OpenID列表 17 private List<String> openIdList; 18 //拉取列表的后一個(gè)用戶(hù)的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 }?
第三步:找到包c(diǎn)om.wtz.vo,新建類(lèi)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:公眾賬號(hào)分組信息</p> 8 */ 9 public class WeixinGroup { 10 //分組id 11 private int id; 12 //分組名稱(chēng) 13 private String name; 14 //分組內(nèi)的用戶(hù)數(shù) 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 }?
第四步:找到包c(diǎn)om.wtz.util,修改類(lèi)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請(qǐng)求工具類(lèi)</p> 33 */ 34 public class WeixinUtil { 35 //需要導(dǎo)入庫(kù)slf4j-api-1.5.10.jar和slf4j-log4j12-1.5.10.jar以及l(fā)og4j-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 * 發(fā)送https請(qǐng)求 43 * 44 * @param requestUrl 請(qǐng)求地址 45 * @param requestMethod 請(qǐng)求方式(GET/POST) 46 * @param outputStr 提交的數(shù)據(jù) 47 * @return JSONObject(通過(guò)JSONObject.get(key)的方式獲取json對(duì)象的屬性值) 48 */ 49 public static JSONObject httpsRequest(String requestUrl,String requestMethod,String outputStr){ 50 //需要導(dǎo)入庫(kù)json-lib-2.2.1-jdk15.jar 51 JSONObject jsonObject = null; 52 53 //創(chuàng)建SSLContext對(duì)象,并使用我們指定的信任管理器初始化 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對(duì)象中得到SSLSocketFactory對(duì)象 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 //設(shè)置請(qǐng)求方式(GET/POST) 74 connection.setRequestMethod(requestMethod); 75 76 //當(dāng)outputStr不為null時(shí)向輸出流寫(xiě)入數(shù)據(jù) 77 if(null != outputStr){ 78 OutputStream outputStream = connection.getOutputStream(); 79 outputStream.write(outputStr.getBytes("UTF-8")); 80 outputStream.close(); 81 } 82 83 //從輸入流讀取返回內(nèi)容 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("連接超時(shí):{}",e); 104 } catch (NoSuchAlgorithmException e) { 105 log.error("https請(qǐng)求異常:{}",e); 106 } catch (NoSuchProviderException e) { 107 log.error("https請(qǐng)求異常:{}",e); 108 } catch (KeyManagementException e) { 109 log.error("https請(qǐng)求異常:{}",e); 110 } catch (MalformedURLException e) { 111 log.error("https請(qǐng)求異常:{}",e); 112 } catch (IOException e){ 113 log.error("https請(qǐng)求異常:{}",e); 114 } catch (Exception e) { 115 log.error("https請(qǐng)求異常:{}",e); 116 } 117 118 return jsonObject; 119 } 120 121 /** 122 * 獲取接口訪(fǎng)問(wèn)憑證 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 //發(fā)起GET請(qǐng)求獲取憑證 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 * 根據(jù)內(nèi)容類(lèi)型判斷來(lái)返回文件的擴(kuò)展名 162 * @param contentType 內(nèi)容類(lèi)型 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 }?
第五步:找到包c(diǎn)om.wtz.util,新建類(lèi)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:高級(jí)接口工具類(lèi)</p> 22 */ 23 public class AdvancedUtil { 24 private static Logger log = LoggerFactory.getLogger(AdvancedUtil.class); 25 26 /** 27 * 獲取用戶(hù)信息 28 * 29 * @param accessToken 接口訪(fǎng)問(wèn)憑證 30 * @param openId 用戶(hù)憑證 31 * @return WeixinUserInfo 32 */ 33 public static UserInfo getUserInfo(String accessToken,String openId){ 34 UserInfo weixinUserInfo = null; 35 //拼接請(qǐng)求地址 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 //獲取用戶(hù)信息 39 JSONObject jsonObject = WeixinUtil.httpsRequest(requestUrl, "GET", null); 40 41 if(null != jsonObject){ 42 try{ 43 weixinUserInfo = new UserInfo(); 44 45 //用戶(hù)的標(biāo)識(shí) 46 weixinUserInfo.setOpenId(jsonObject.getString("openid")); 47 48 //關(guān)注狀態(tài)(1是關(guān)注,0是未關(guān)注),未關(guān)注時(shí)獲取不到其余信息 49 weixinUserInfo.setSubscribe(jsonObject.getInt("subscribe")); 50 51 //用戶(hù)關(guān)注時(shí)間 52 weixinUserInfo.setSubscribeTime(jsonObject.getString("subscribe_time")); 53 54 //昵稱(chēng) 55 weixinUserInfo.setNickname(jsonObject.getString("nickname")); 56 57 //用戶(hù)的性別(1是男性,2是女性,0是未知) 58 weixinUserInfo.setSex(jsonObject.getInt("sex")); 59 60 //用戶(hù)所在的國(guó)家 61 weixinUserInfo.setCountry(jsonObject.getString("country")); 62 63 //用戶(hù)所在的省份 64 weixinUserInfo.setProvince(jsonObject.getString("province")); 65 66 //用戶(hù)所在的城市 67 weixinUserInfo.setCity(jsonObject.getString("city")); 68 69 //用戶(hù)的語(yǔ)言,簡(jiǎn)體中文為zh_CN 70 weixinUserInfo.setLanguage(jsonObject.getString("language")); 71 72 //用戶(hù)頭像 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("用戶(hù){}已取消關(guān)注",weixinUserInfo.getOpenId()); 80 }else{ 81 int errorCode = jsonObject.getInt("errcode"); 82 String errorMsg = jsonObject.getString("errmsg"); 83 log.error("獲取用戶(hù)信息失敗 errorcode:{} errormsg:{}",errorCode,errorMsg); 84 } 85 } 86 } 87 return weixinUserInfo; 88 } 89 90 /** 91 * 獲取關(guān)注者列表 92 * 93 * @param accessToken 調(diào)用接口憑證 94 * @param nextOpenId 第一個(gè)拉取nextOpenId,不填默認(rèn)從頭開(kāi)始拉取 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 //拼接請(qǐng)求地址 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 //獲取關(guān)注者列表 109 JSONObject jsonObject = WeixinUtil.httpsRequest(requestUrl, "GET", null); 110 111 //如果請(qǐng)求成功 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 //獲取接口訪(fǎng)問(wèn)憑證 126 String accessToken = WeixinUtil.getToken(Parameter.appId,Parameter.appSecret).getAccessToken(); 127 System.out.println("accessToken:" + accessToken); 128 129 //獲取關(guān)注者列表 130 UserList weixinUserList = getUserList(accessToken,""); 131 System.out.println("總關(guān)注用戶(hù)數(shù):" + weixinUserList.getTotal()); 132 System.out.println("本次獲取用戶(hù)數(shù):" + 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 //獲取用戶(hù)信息 140 user = getUserInfo(accessToken,(String)list.get(i)); 141 System.out.println("OpenId:" + user.getOpenId()); 142 System.out.println("關(guān)注狀態(tài):" + user.getSubscribe()); 143 System.out.println("關(guān)注時(shí)間:" + (new SimpleDateFormat("yyyy-MM-dd HH:mm-ss").format(new Date(new Long(user.getSubscribeTime()))))); 144 System.out.println("昵稱(chēng):" + user.getNickname()); 145 System.out.println("性別:" + user.getSex()); 146 System.out.println("國(guó)家:" + user.getCountry()); 147 System.out.println("省份:" + user.getProvince()); 148 System.out.println("城市:" + user.getCity()); 149 System.out.println("語(yǔ)言:" + user.getLanguage()); 150 System.out.println("頭像:" + user.getHeadImgUrl()); 151 System.out.println("unionid:" + user.getUnionid()); 152 System.out.println("====================================="); 153 } 154 } 155 }高級(jí)接口(獲取用戶(hù)信息和獲取關(guān)注者列表)完成
轉(zhuǎn)載于:https://www.cnblogs.com/wangtianze/p/6760592.html
總結(jié)
以上是生活随笔為你收集整理的Java微信二次开发(八)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Java NIO系列教程(五)Buffe
- 下一篇: Linux中的gdb调试方法总结