package cn.xxxx.utils;
import javax.annotation.Resource;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.junit.Test;
import cn.xxxxx.domain.Userdata;
import cn.xxxxx.UserdataService;
public class EveryData {
// 访问每天变化的url
private static final String USERSUBDATAURL = "https://api.weixin.qq.com/datacube/getusersummary";
// 访问每天总数量的url
private static final String USERALLDATAURL = "https://api.weixin.qq.com/datacube/getusercumulate";
//昨天的日期
private String yestoday = NowTimeUtils.getYestoday();
//service层接口
@Resource
private UserdataService uds;
//注入的动态获取token的bean
@Resource
private WeixinBean bean;
/**
* 每天凌晨读取昨天用户统计数据并存储到数据库中,该方法通过定时器每天凌晨0点5分执行
*
* @throws Exception
*/
@Test
public void getUserDataWithEveryDay() throws Exception {
JSONObject jsonobject = new JSONObject();
jsonobject.put("begin_date", yestoday);
jsonobject.put("end_date", yestoday);
//获得每天新增关注的人数
Integer newuser = Integer.parseInt(getKv(jsonobject, "new_user",
USERSUBDATAURL));
//获得昨天取消关注的人数
Integer canceluser = Integer.parseInt(getKv(jsonobject, "cancel_user",
USERSUBDATAURL));
//获得总的人数
Integer cumulateuser = Integer.parseInt(getKv(jsonobject,
"cumulate_user", USERALLDATAURL));
//表关联对象
Userdata ud = new Userdata();
ud.setDay(yestoday);
ud.setCanceluser(canceluser);
ud.setCumulateuser(cumulateuser);
ud.setNewuser(newuser);
//插入数据库
uds.insert(ud);
}
private String getKv(JSONObject jsonobject, String key, String url) {
//发送请求,携带json参数
url=url+"?access_token="+bean.getToken();
String result = HttpUtils.sendJson(url, jsonobject);
JSONObject jsonObject;
String value = null;
try {
jsonObject = new JSONObject(result);
JSONArray jsonArray = (JSONArray) jsonObject.get("list");
//如果里面没有,那么新增和取关都设置为0
if (jsonArray == null || jsonArray.length() <= 0) {
return "0";
}
jsonObject = (JSONObject) jsonArray.get(0);
value = jsonObject.getString(key);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
}
}
二话不说,直接粘代码体现思路,但其中一些类是自有的,涉及公司命名等,不能粘贴