java 判断用户是否取消关注微信公众号

今天在做项目的时候,需要判断用户是否取消关注了公众号,下面开始进入正题

 

一、获取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;
}

 

转载于:https://www.cnblogs.com/qian-w/p/9850182.html

你可能感兴趣的:(java 判断用户是否取消关注微信公众号)