今天在做項目的時候,需要判斷用戶是否取消關注了公眾號,下面開始進入正題
一、獲取access_token
public static String getAccessTokes() {
String access_token = "";
String grant_type = "client_credential";// 獲取access_token填寫client_credential
String AppId = "**";// 第三方用戶唯一憑證
String secret = "**";// 第三方用戶唯一憑證密鑰,即appsecret
// 這個url鏈接地址和參數皆不能變
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + AppId + "&secret="
+ secret;
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必須是get方式請求
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 連接超時30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 讀取超時30秒
http.connect();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String message = new String(jsonBytes, "UTF-8");
JSONObject demoJson = JSONObject.parseObject(message);
access_token = demoJson.getString("access_token");
System.out.println("getAccessToke------------------JSON字符串:" + demoJson);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return access_token;
}
二、判斷是否關注
public boolean judgeIsFollow(String access_token,String openid){
Integer subscribe = 0;
String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必須是get方式請求
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String message = new String(jsonBytes, "UTF-8");
JSONObject demoJson = JSONObject.parseObject(message);
System.out.println("JSON字符串:"+demoJson);
subscribe = demoJson.getIntValue("subscribe"); // 此字段為關注字段 關注為1 未關注為0
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return 1==subscribe?true:false;
}
