钉钉考情打卡记录

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38292691/article/details/87925026
package com.example.demo.dingding.constant;

public class DingDingConstant {

    public static String APP_KEY = "";
    public static String APP_SECRET = "";
    public static String getAccessTokenUrl = "https://oapi.dingtalk.com/gettoken?appkey=%s&appsecret=%s";
    public static String daKaJiLu = "https://oapi.dingtalk.com/attendance/listRecord?access_token=%s";
    public static String getUsersUrl = "https://oapi.dingtalk.com/user/getDeptMember?access_token=%s&deptId=%s";
    public static String departmentList = "https://oapi.dingtalk.com/department/list?access_token=%s";
}
package com.example.demo.dingding.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.dingding.beans.Attendance;
import com.example.demo.dingding.dao.AttendanceDao;
import com.example.demo.util.HttpUtils;
import com.example.demo.util.JsonFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static com.example.demo.dingding.constant.DingDingConstant.*;

@Service
public class DngDingService {

    @Autowired
    AttendanceDao attendanceDao;

    private Log log = LogFactory.getLog(DngDingService.class);

    
    private String accessToken;

    private String getAccessToken() {
        getAccessTokenUrl = String.format(getAccessTokenUrl, APP_KEY, APP_SECRET);
        JSONObject tokenJSON = HttpUtils.doGet(getAccessTokenUrl);
        log.info(JSON.toJSONString(tokenJSON));
        return tokenJSON.getString("access_token");
    }

    private List<String> getDeptList() {
        this.accessToken = getAccessToken();
        departmentList = String.format(departmentList, accessToken);
        JSONObject departmentListJSON = HttpUtils.doGet(departmentList);
        Object department = departmentListJSON.get("department");
        log.info("department--->" + JsonFormatUtils.toFormat(JSON.toJSONString(department), true, true));
        List list = JSONObject.parseObject(JSON.toJSONString(department), List.class);
        List<String> deptList = new ArrayList<>();
        for (Object m : list) {
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(m));
            deptList.add(String.valueOf(jsonObject.getString("id")));
        }
        return deptList;
    }

    private List getUserIds() {
        List resUserIds = new ArrayList();
        List<String> deptList = getDeptList();
        Collections.reverse(deptList);
        for (String deptId : deptList) {
            String getUserIds = String.format(getUsersUrl, accessToken, deptId);
            HttpUtils httpUtils = new HttpUtils();
            JSONObject jsonObject = httpUtils.doGet(getUserIds);
            log.info("users" + JSON.toJSONString(jsonObject));
            resUserIds.addAll(JSONObject.parseObject(JSON.toJSONString(jsonObject.get("userIds")), List.class));
        }

        return resUserIds;
    }

    public void getRecords() {
        List userIds = getUserIds();

        String recordUrl = String.format(daKaJiLu, accessToken);
        JSONObject params = new JSONObject();

        params.put("checkDateFrom", "2019-02-17 00:00:00");
        params.put("checkDateTo", "2019-02-22 19:47:00");
        params.put("userIds", userIds);
        params.put("isI18n", false);

        JSONObject res = HttpUtils.doPost(recordUrl, params, "utf-8");
        String result = JSON.toJSONString(res);
        log.info(JsonFormatUtils.toFormat(result, true, true));

        List recordResult = JSONObject.parseObject(res.getString("recordresult"), List.class);
        for (int i = 0; i < recordResult.size(); i++) {
            Object o = recordResult.get(i);
            Attendance attendance = JSONObject.parseObject(JSON.toJSONString(o), Attendance.class);
            attendanceDao.insertAttendance(attendance);
        }
    }
}
package com.example.demo.util;

public class JsonFormatUtils {


    public static String toFormat(String content, boolean indent, boolean colonWithSpace) {
        if (content == null) return null;
        StringBuilder sb = new StringBuilder();
        int count = 0;
        boolean inString = false;
        String tab = "\t";
        for (int i = 0; i < content.length(); i++) {
            char ch = content.charAt(i);
            switch (ch) {
                case '{':
                case '[':
                    sb.append(ch);
                    if (!inString) {
                        if (indent) {
                            sb.append("\n");
                            count++;
                            for (int j = 0; j < count; j++) {
                                sb.append(tab);
                            }
                        }

                    }
                    break;
                case '\uFEFF': //非法字符
                    if (inString) sb.append(ch);
                    break;
                case '}':
                case ']':
                    if (!inString) {
                        if (indent) {
                            count--;
                            sb.append("\n");
                            for (int j = 0; j < count; j++) {
                                sb.append(tab);
                            }
                        }

                        sb.append(ch);
                    } else {
                        sb.append(ch);
                    }
                    break;
                case ',':
                    sb.append(ch);
                    if (!inString) {
                        if (indent) {
                            sb.append("\n");
                            for (int j = 0; j < count; j++) {
                                sb.append(tab);
                            }
                        } else {
                            if (colonWithSpace) {
                                sb.append(' ');
                            }
                        }
                    }
                    break;
                case ':':
                    sb.append(ch);

                    if (!inString) {
                        if (colonWithSpace) {  //key名称冒号后加空格
                            sb.append(' ');
                        }
                    }
                    break;
                case ' ':
                case '\n':
                case '\t':
                    if (inString) {
                        sb.append(ch);
                    }
                    break;
                case '"':
                    if (i > 0 && content.charAt(i - 1) != '\\') {
                        inString = !inString;
                    }
                    sb.append(ch);
                    break;
                default:
                    sb.append(ch);
                    break;
            }
        }
        return sb.toString();
    }
}
package com.example.demo.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.client.utils.HttpClientUtils;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class); // 日志记录

    private static RequestConfig requestConfig;

    static {
        // 设置请求和传输超时时间
        requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
    }

    /**
     * post请求传输json参数
     *
     * @return
     */
    public static JSONObject doPost(String url, JSONObject jsonParam, String charset) {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        // 设置请求和传输超时时间
        httpPost.setConfig(requestConfig);
        try {
            if (null != jsonParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), charset);
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功,并得到响应
            jsonResult = getJsonObject(url, jsonResult, result);
        } catch (IOException e) {
            logger.error("post请求提交失败:" + url, e);
        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }

    private static JSONObject getJsonObject(String url, JSONObject jsonResult, CloseableHttpResponse result) {
        if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String str = "";
            try {
                // 读取服务器返回过来的json字符串数据
                str = EntityUtils.toString(result.getEntity(), "utf-8");
                // 把json字符串转换成json对象
                jsonResult = JSONObject.parseObject(str);
            } catch (Exception e) {
                logger.error("post请求提交失败:" + url, e);
            }
        }
        return jsonResult;
    }

    /**
     * post请求传输String参数 例如:name=Jack&sex=1&type=2
     * Content-type:application/x-www-form-urlencoded
     *
     * @return
     */
    public static JSONObject doPost(String url, String strParam) {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        try {
            if (null != strParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(strParam, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/x-www-form-urlencoded");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功,并得到响应
            jsonResult = getJsonObject(url, jsonResult, result);
        } catch (IOException e) {
            logger.error("post请求提交失败:" + url, e);
        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */
    public static JSONObject doGet(String url) {
        // get请求返回结果
        JSONObject jsonResult = null;
        CloseableHttpClient client = HttpClients.createDefault();
        // 发送get请求
        HttpGet request = new HttpGet(url);
        requestConfig = RequestConfig.custom()
                .setConnectTimeout(30000)
                .setSocketTimeout(30000)
                .build();
        request.setConfig(requestConfig);
        try {
            CloseableHttpResponse response = client.execute(request);

            // 请求发送成功,并得到响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                HttpEntity entity = response.getEntity();
                String strResult = EntityUtils.toString(entity, "utf-8");
                // 把json字符串转换成json对象
                jsonResult = JSONObject.parseObject(strResult);
            } else {
                logger.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:" + url, e);
        } finally {
            request.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * get请求,参数放在map里
     * @param url 请求地址
     * @param map 参数map
     * @return 响应
     */
    public static String getMap(String url,Map<String,String> map)
    {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        for(Map.Entry<String,String> entry : map.entrySet())
        {
            pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        }
        CloseableHttpResponse response = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            builder.setParameters(pairs);
            HttpGet get = new HttpGet(builder.build());
            response = httpClient.execute(get);
            if(response != null && response.getStatusLine().getStatusCode() == 200)
            {
                HttpEntity entity = response.getEntity();
                result = entityToString(entity);
            }
            return result;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
                if(response != null)
                {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    private static String entityToString(HttpEntity entity) throws IOException {
        String result = null;
        if(entity != null)
        {
            long lenth = entity.getContentLength();
            if(lenth != -1 && lenth < 2048)
            {
                result = EntityUtils.toString(entity,"UTF-8");
            }else {
                InputStreamReader reader1 = new InputStreamReader(entity.getContent(), "UTF-8");
                CharArrayBuffer buffer = new CharArrayBuffer(2048);
                char[] tmp = new char[1024];
                int l;
                while((l = reader1.read(tmp)) != -1) {
                    buffer.append(tmp, 0, l);
                }
                result = buffer.toString();
            }
        }
        return result;
    }
}
package com.example.demo.dingding.dao;

import com.example.demo.dingding.beans.Attendance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class AttendanceDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public void insertAttendance(Attendance attendance) {
        StringBuilder sql = new StringBuilder();
        sql.append("insert into attendance_record");
        sql.append("(checkType,\n" +
                "\t\t\t gmtModified,\n" +
                "\t\t\t planCheckTime,\n" +
                "\t\t\t corpId,\n" +
                "\t\t\t locationResult,\n" +
                "\t\t\t userLongitude,\n" +
                "\t\t\t isLegal,\n" +
                "\t\t\t baseCheckTime,\n" +
                "\t\t\t groupId,\n" +
                "\t\t\t timeResult,\n" +
                "\t\t\t gmtCreate,\n" +
                "\t\t\t userId,\n" +
                "\t\t\t deviceId,\n" +
                "\t\t\t userAccuracy,\n" +
                "\t\t\t userAddress,\n" +
                "\t\t\t userLatitude,\n" +
                "\t\t\t classId,\n" +
                "\t\t\t workDate,\n" +
                "\t\t\t sourceType,\n" +
                "\t\t\t userCheckTime,\n" +
                "\t\t\t locationMethod,\n" +
                "\t\t\t planId,id)");
        sql.append("values");
        sql.append("(?,\n" +
                "?,\n" +
                "?,\n" +
                "?,\n" +
                "?,\n" +
                "?,\n" +
                "?,\n" +
                "?,\n" +
                "?,\n" +
                "?,\n" +
                "?,\n" +
                "?,\n" +
                "?,\n" +
                "?,\n" +
                "?,\n" +
                "?,\n" +
                "?,\n" +
                "?,\n" +
                "?,\n" +
                "?,\n" +
                "?,\n" +
                "?,\n" +
                "?)");
        jdbcTemplate.update(sql.toString()
                , attendance.getCheckType()
                , attendance.getGmtModified()
                , attendance.getPlanCheckTime()
                , attendance.getCorpId()
                , attendance.getLocationResult()
                , attendance.getUserLongitude()
                , attendance.getIsLegal()
                , attendance.getBaseCheckTime()
                , attendance.getGroupId()
                , attendance.getTimeResult()
                , attendance.getGmtCreate()
                , attendance.getUserId()
                , attendance.getDeviceId()
                , attendance.getUserAccuracy()
                , attendance.getUserAddress()
                , attendance.getUserLatitude()
                , attendance.getClassId()
                , attendance.getWorkDate()
                , attendance.getSourceType()
                , attendance.getUserCheckTime()
                , attendance.getLocationMethod()
                , attendance.getPlanId()
                , attendance.getId()
        );
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38292691/article/details/87925026