有个特别恶心的地方就是打卡信息只能最多一次取七天的。所以要注意一下; 时间格式:2018-05-01
钉钉突然改接口了,直接获取是被拒绝了,加了分页限制,加了人数限制,头大,之前得方法不能用了,重新写了版,最多一次获取50个人的考勤,并且这些人的考勤记录一次只能获取50条,我想了个办法中心思想就是首先拆分公司人员的dingId的列表,拆成每50个一组,然后限制分页最大50个每页,50个人的打卡记录肯定大于最大限制,每次获取返回的考勤记录判断它给返回的hasMore是不是true是的话还将这50个人作为条件,偏移量加50,查询下一部分的考勤记录,如果是false则说明已经获取这50个人的全部数据,那么则将之后的50个人作为新的条件,继续以上判断,如果大家有更好的方法欢迎来留言,学习一下。环境是jdk 1.8,maven 3.5.4,tomcat 7.0.8
package ding;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class DingRecordSyncController {
private static String accessTokenUrl = "https://oapi.dingtalk.com/gettoken";//通用
private static String corpId = "你公司自己的corpId,在钉钉管理员账号设置里面能看到";
private static String corpSecret = "你公司自己的corpId,在钉钉管理员账号设置里面能看到";
public static String getAccessToken() {
Map map = new HashMap<>();
map.put("corpid",corpId);
map.put("corpsecret",corpSecret);
return httpGetStringResult(accessTokenUrl, map);//获取access_token
}
public static String httpGetStringResult(String url,Map param){
String content = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
if(param != null && !param.isEmpty()){
StringBuffer strparams = new StringBuffer();
for (Map.Entry map : param.entrySet()) {
strparams.append(map.getKey()).append("=").append(map.getValue().toString()).append("&");
}
strparams = strparams.deleteCharAt(strparams.length()-1);
url = url + "?" + strparams;
}
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
content = EntityUtils.toString(entity,"UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(null!=response){
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
}
public static String doPost(String requestUrl,JSONObject json){
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(requestUrl);
post.setHeader("Content-Type", "application/json");
post.addHeader("Authorization", "Basic YWRtaW46");
String result = "";
try {
StringEntity s = new StringEntity(json.toString(), "utf-8");
s.setContentEncoding(new BasicHeader("contentType",
"application/json"));
post.setEntity(s);
// 发送请求
HttpResponse httpResponse = client.execute(post);
// 获取响应输入流
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
result = strber.toString();
System.out.println(result);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
System.out.println("请求服务器成功,做相应处理");
} else {
System.out.println("请求服务端失败");
}
} catch (Exception e) {
System.out.println("请求异常");
throw new RuntimeException(e);
}
return result;
}
public static List getAttendances(List users, String workDateFrom, String workDateTo,String access_Token) {
List list = Arrays.asList("121212121212121212","121212121212324345345","。。。自己公司的员工钉钉ID");
int listSize=list.size();
int toIndex = 50;
for(int i = 0;i < list.size();i += 50){
if(i+50 > listSize){ //作用为toIndex最后没有50条数据则剩余几条newList中就装几条
toIndex = listSize-i;
}
List newList = list.subList(i,i + toIndex);
Boolean hasMore = true;
int offset = 0;//为了分页
do{
Map mapParam = new HashMap<>();
mapParam.put("workDateFrom", workDateFrom);
mapParam.put("workDateTo", workDateTo);
mapParam.put("userIdList", newList);
mapParam.put("offset", offset * 50);
mapParam.put("limit", 50);
String attendanceStr = getAttendance(mapParam, access_Token);
JSONObject firstJson = JSONObject.parseObject(attendanceStr);
hasMore = firstJson.getBoolean("hasMore");
JSONArray recordFirst = firstJson.getJSONArray("recordresult");//当前部门下的userList
for(int j = 0;j < recordFirst.size(); j++) {
JSONObject record = recordFirst.getJSONObject(j);
AttendanceQvo attendanceQvo = new AttendanceQvo();
attendanceQvo.setCheckType(record.getString("checkType"));
attendanceQvo.setUserId(record.getString("userId"));
attendanceQvo.setWorkDate(record.getLong("workDate"));
attendanceQvo.setUserCheckTime(record.getLong("userCheckTime"));
users.add(attendanceQvo);
}
if(hasMore) {//有下一页偏移量加一
offset++;
}
} while (hasMore);
}
return users;
}
public static String getAttendance(Map map ,String access_token_str) {
String dingDingAttendance = "https://oapi.dingtalk.com/attendance/list?access_token="+access_token_str;
JSONObject jsonObject = new JSONObject();
jsonObject.put("workDateFrom",map.get("workDateFrom"));
jsonObject.put("workDateTo",map.get("workDateTo"));
jsonObject.put("limit",map.get("limit"));
jsonObject.put("offset",map.get("offset"));
jsonObject.put("userIdList",map.get("userIdList"));
return doPost(dingDingAttendance,jsonObject);//获取考勤记录
}
/* * @Description: -1是前一天, +1是后一天
* @Date: 17:28 2018/5/29
*/
public static String getPreDayOrAfterDay(String current, int flag) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();//获取日历实例
try {
calendar.setTime(sdf.parse(current));
} catch (ParseException e) {
e.printStackTrace();
}
calendar.add(Calendar.DAY_OF_MONTH, flag); //设置为前一天
String yesterday = sdf.format(calendar.getTime());//获得前一天
return yesterday;
}
public static void main(String[] args) {
List users = new ArrayList<>();
Date date = new Date();
String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
String yesterday = getPreDayOrAfterDay(currentDate, -1);
String workDateFrom = yesterday + " " + "06:00:00";
String workDateTo = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);//当前时间
String access_token_str = getAccessToken();//获取access_token
JSONObject jsonStr = JSONObject.parseObject(access_token_str); //转json结构
String access_Token = jsonStr.getString("access_token");//获取access_Token
getAttendances(users, workDateFrom,workDateTo, access_Token);//凌晨的
System.out.println("获取从昨天六点到当前时间的打卡记录"+ Arrays.asList(users));
}
}
accessTokenUrl : https://oapi.dingtalk.com/gettoken
@Data
public class AttendanceQvo implements Serializable{
private String checkType; //上下午
private String userId; //员工ID
private long userCheckTime;//实际打卡时间
private long workDate; //工作日
}