您的位置:首页 > 移动开发 > 微信开发

微信公众号开发之用户分组

2016-12-26 18:15 183 查看
具体参照微信官方文档

创建用户分组

/**
* 创建分组
* @param groupName 分组名
* @return Integer 分组ID
*/
public static Integer createPrizeDrawGroup(String groupName){
String url = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token="+getGlobalToken();
JSONObject json = new JSONObject();
JSONObject jsonParent = new JSONObject();
json.put("name", groupName);
jsonParent.put("group", json);

JSONObject demoJson = null;
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("POST"); // 必须是POST方式请求
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
http.getOutputStream().write(jsonParent.toString().getBytes());
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");
demoJson = JSONObject.fromObject(message);

//System.out.println("JSON字符串:"+demoJson);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return demoJson.getJSONObject("group").getInt("id");
}


批量移动用户分组

/**
* 移动用户分组
* @param list openID list
* @param id 分组ID
* @return 操作成功:true 失败:false
*/
public boolean updateGroup(List<String> list,Integer id){
String url = "https://api.weixin.qq.com/cgi-bin/groups/members/batchupdate?access_token="+getGlobalToken();
JSONObject json = new JSONObject();
json.put("openid_list", list);
json.put("to_groupid", id);
JSONObject demoJson = null;
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("POST"); // 必须是get方式请求
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
http.getOutputStream().write(json.toString().getBytes());
//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");
demoJson = JSONObject.fromObject(message);
System.out.println("JSON字符串:"+demoJson);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return demoJson.getInt("errcode")==1?true:false;
}


我有空再来添加详细描述吧!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  微信 用户分组