import java.net.HttpURLConnection; import java.net.URL;
一、获取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;
}
注意事项 :
微信有两种token,一种为access_token一种为token ,此处用的是 access_token
该博客主要围绕微信公众号开发,给出了获取access_token的代码,通过向特定URL发送GET请求解析返回的JSON数据得到。还提供判断用户是否关注公众号的代码,利用access_token和openid获取用户信息,根据返回结果中的subscribe字段判断。同时提醒注意微信有两种token,此处用的是access_token。

1537

被折叠的 条评论
为什么被折叠?



