1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 微信通过用户openID获取UnionID

微信通过用户openID获取UnionID

时间:2024-07-05 12:59:38

相关推荐

微信通过用户openID获取UnionID

获取用户基本信息(包括UnionID机制)

开发者可通过OpenID来获取用户基本信息。请使用https协议。

接口调用请求说明http请求方式: GEThttps://api./cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

参数说明

所以首先需要拿到access_token才能来调用接口。

获取access_token

接口调用请求说明

https请求方式: GEThttps://api./cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

参数说明

Map<String,String> params = new HashMap<String,String>();params.put("appid", xxx);params.put("secret", xxx);params.put("grant_type", "client_credential");result = HttpGetUtil.httpRequestToString("https://api./cgi-bin/token", params);JSONObject jsonObject = JSONObject.fromObject(result);access_token = jsonObject.get("access_token").toString();

拿到access_token后再去调用获取用户信息的接口

https://api./cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

Map<String,String> params = new HashMap<String,String>(); params.put("access_token",access_token);params.put("lang","zh_CN");params.put("openid",xxx);result = HttpGetUtil.httpRequestToString("https://api./cgi-bin/user/info", params);jsonObject = JSONObject.fromObject(result);String subscribe = jsonObject.get("subscribe").toString();

注意:当subscribe为0时,说明用户未关注公众号,拉取不到其他信息。

HttpGetUtil.java

public class HttpGetUtil {public static String httpRequestToString(String url, Map<String,String> params) {String result = null;try {InputStream is = httpRequestToStream(url, params);BufferedReader in = new BufferedReader(new InputStreamReader(is,"UTF-8"));StringBuffer buffer = new StringBuffer();String line = "";while ((line = in.readLine()) != null) {buffer.append(line);}result = buffer.toString();} catch (Exception e) {return null;}return result;}private static InputStream httpRequestToStream(String url,Map<String, String> params) {InputStream is = null;try {String parameters = "";boolean hasParams = false;for(String key : params.keySet()){String value = URLEncoder.encode(params.get(key), "UTF-8");parameters += key +"="+ value +"&";hasParams = true;}if(hasParams){parameters = parameters.substring(0, parameters.length()-1);}url += "?"+ parameters;URL u = new URL(url);HttpURLConnection conn = (HttpURLConnection) u.openConnection();conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");conn.setRequestProperty("Accept-Charset", "UTF-8");conn.setRequestProperty("contentType", "utf-8");conn.setConnectTimeout(50000); conn.setReadTimeout(50000);conn.setDoInput(true);//设置请求方式,默认为GETconn.setRequestMethod("GET");is = conn.getInputStream();} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return is;}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。