有一項目,需要刷新最新的用戶信息之后再給部分用戶推送消息,之前選擇微信的get接口,使用用戶openid獲取單個用戶的信息,然后比對入庫,一萬個粉絲大概需要30多分鍾
比較被動
然后使用批量獲取,速度得到極大提升
批量獲取用戶基本信息
http請求方式: POST https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=ACCESS_TOKEN
POST數據示例
這里吐槽一下,參數不是標准json,不是標准json,不是標准json,不是標准json,不是標准json,不是標准json,不是標准json,而是數組,返回值也不是表准json
這就要多些好幾行代碼來包裝一下了
首先需要在數據庫里拿出一部分用戶,然后取openid
List<CustomerWechat> customerWechats = cwd.get100StartById(session, startId);
如果返回值不是空的話
就進行處理
JSONObject[] myList = new JSONObject[customerWechats.size()]; int i = 0; for (CustomerWechat cw : customerWechats) { JSONObject jb = new JSONObject(); jb.put("openid", customerWechats.get(i).getOpenid()); jb.put("lang", "zh_CN"); myList[i] = jb; i++; }
把數據再組合一下
JSONObject jsonObject = new JSONObject(); jsonObject.put("user_list", myList);
然后再從數據庫里把接口地址拿出來
ApiWechat api = awd.getApiGetcustomerBatch(session);
然后把token加上
String url = api.getUrl().replace("ACCESS_TOKEN", at.getAccess_token());
然后
發器post等着返回數據就完事兒了
// 通過HttpPost來發送post請求 HttpPost httpPost = new HttpPost(url); String jsonString = jsonObject.toJSONString(); StringEntity entityStr = new StringEntity(jsonString, "UTF-8"); httpPost.setEntity(entityStr); CloseableHttpResponse response = null; CloseableHttpClient httpClient = HttpClients.createDefault(); response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); String resp = ""; resp = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity);//釋放資源
然后
把返回值沒用的數據都刪掉
里邊的數據就不管了,都是大家最愛的json
String resArray = resp.substring(resp.indexOf("["), resp.length() - 1);
最后再把處理之后的數據,也就是表准的json了,轉換為對象列表,就行了
List<CustomerWechat> customerList = JSONObject.parseArray(resArray, CustomerWechat.class);