Java版得力API接口文档实现之接口加密

  1. 关于接口对接加密的问题
    直接上代码了:
    1)ApiRequest
package handler;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import util.JsonUtil;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

public class ApiRequest {

    private final String url;
    private final Map<String, String> headerMap;
    private final String jsonParams;

    public ApiRequest(String url, Map<String, String> headerMap, String jsonParams) {
        this.url = url;
        this.headerMap = headerMap;
        this.jsonParams = jsonParams;
        System.out.println("请求header: " + JsonUtil.mapToJson(headerMap));
    }

    public String doRequest() {
        if (null == jsonParams) {
            return "请求参数为空";
        }
        // 通过httpclient构造一个post请求
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(5000)
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .build();
        httpPost.setConfig(requestConfig);

        // 设置请求的 header
        for (Map.Entry<String, String> s : headerMap.entrySet()) {
            httpPost.setHeader(s.getKey(), s.getValue());
        }

        // 设置请求数据类型为json
        httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");

        // 设置请求的 body
        HttpEntity entity = new StringEntity(jsonParams, ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity);

        try (CloseableHttpClient httpclient = HttpClients.createDefault();
             CloseableHttpResponse httpResp = httpclient.execute(httpPost)) {
            if (Objects.nonNull(httpResp)) {
                return EntityUtils.toString(httpResp.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return "";
    }
}

  1. ApiService.java
package service;

import bo.RespBase;
import bo.req.*;
import bo.resp.*;
import com.fasterxml.jackson.core.type.TypeReference;
import handler.ApiRequest;
import util.Encode;
import util.JsonUtil;
import util.TimeUtil;

import java.util.HashMap;
import java.util.Map;

public final class ApiService {

   /**
    * <b>此处的接口地址需要开发人员自己替换为生产环境的<b/>
    */
   private static final String DOMAIN = "http://s-api.delicloud.com";
   /**
    * <b>此处填写实际的 App-Key<b/>
    */
   private static final String APP_KEY = "a34ef2f65bd25fa6f48bbf078a404a73";
   /**
    * <b>此处填写实际的 App-Secret<b/>
    */
   private static final String APP_SECRET = "bjyocfomke8itencts06hpnpnq4meg28";
   private static final String DepartmentURL = "/v2.0/department";
   private static final String DepartmentQueryURL = "/v2.0/department/query";
   private static final String DepartmentExtURL = "/v2.0/department/ext";
   private static final String EmployeeURL = "/v2.0/employee";
   private static final String EmployeeQueryURL = "/v2.0/employee/query";
   private static final String EmployeeExtURL = "/v2.0/employee/ext";
   private static final String CloudAppApiURL = "/v2.0/cloudappapi";

   private final String domain;

   public ApiService() {
       this.domain = DOMAIN;
   }

   public ApiService(String domain) {
       this.domain = domain;
   }

   /**
    * 查询部门信息列表
    *
    * @param pageReq 分页请求参数
    * @return 请求结果
    */
   public RespBase<PageResp<DepartmentDataResp>> departmentQuery(PageReq pageReq) {
       String jsonParams = JsonUtil.objectToJson(pageReq);
       System.out.println("请求json: " + jsonParams);

       // 获取请求头
       Map<String, String> headerMap = this.getHeaderMap(DepartmentQueryURL);

       ApiRequest request = new ApiRequest(this.domain + DepartmentQueryURL, headerMap, jsonParams);
       String body = request.doRequest();
       RespBase<PageResp<DepartmentDataResp>> respBase = JsonUtil.jsonToObject(body, new TypeReference<RespBase<PageResp<DepartmentDataResp>>>() {});
       return respBase;
   }

   /**
    * 为部门设置外部ID
    *
    * @param extReq 请求参数
    * @return 请求结果
    */
   public RespBase<Void> departmentExt(DepartmentExtReq extReq) {
       String jsonParams = JsonUtil.objectToJson(extReq);
       System.out.println("请求json: " + jsonParams);

       // 获取请求头
       Map<String, String> headerMap = this.getHeaderMap(DepartmentExtURL);

       ApiRequest request = new ApiRequest(this.domain + DepartmentExtURL, headerMap, jsonParams);
       String body = request.doRequest();
       RespBase<?> respBase = JsonUtil.jsonToObject(body, RespBase.class);
       return (RespBase<Void>) respBase;
   }

   /**
    * 添加/修改部门信息
    *
    * @param departmentCreateReq 请求参数
    * @return 请求结果
    */
   public RespBase<DepartmentDataResp> departmentRequest(DepartmentCreateReq departmentCreateReq) {
       String jsonParams = JsonUtil.objectToJson(departmentCreateReq);
       System.out.println("请求json: " + jsonParams);

       // 获取请求头
       Map<String, String> headerMap = this.getHeaderMap(DepartmentURL);

       ApiRequest request = new ApiRequest(this.domain + DepartmentURL, headerMap, jsonParams);
       String body = request.doRequest();
       RespBase<DepartmentDataResp> respBase = JsonUtil.jsonToObject(body, new TypeReference<RespBase<DepartmentDataResp>>() {});
       return respBase;
   }

   /**
    * 添加或者编辑员工信息
    *
    * @param employeeCreateReq 员工信息
    * @return 请求结果
    */
   public RespBase<EmployeeDataResp> employeeRequest(EmployeeCreateReq employeeCreateReq) {
       String jsonParams = JsonUtil.objectToJson(employeeCreateReq);
       System.out.println("请求json: " + jsonParams);

       // 获取请求头
       Map<String, String> headerMap = this.getHeaderMap(EmployeeURL);
       ApiRequest request = new ApiRequest(this.domain + EmployeeURL, headerMap, jsonParams);
       String body = request.doRequest();
       RespBase<EmployeeDataResp> respBase = JsonUtil.jsonToObject(body, new TypeReference<RespBase<EmployeeDataResp>>() {});
       return respBase;
   }

   /**
    * 批量获取e+平台系统中内的员工信息
    *
    * @param pageReq 分页查询参数
    * @return 请求结果
    */
   public RespBase<PageResp<EmployeeBatchDataResp>> employeeQuery(PageReq pageReq) {
       String jsonParams = JsonUtil.objectToJson(pageReq);
       System.out.println("请求json: " + jsonParams);

       // 获取请求头
       Map<String, String> headerMap = this.getHeaderMap(EmployeeQueryURL);
       ApiRequest request = new ApiRequest(this.domain + EmployeeQueryURL, headerMap, jsonParams);
       String body = request.doRequest();
       RespBase<PageResp<EmployeeBatchDataResp>> respBase = JsonUtil.jsonToObject(body, new TypeReference<RespBase<PageResp<EmployeeBatchDataResp>>>() {});
       return respBase;
   }

   /**
    * 为员工设置外部id
    *
    * @param employeeExtReq 请求参数
    * @return 请求结果
    */
   public RespBase<Void> employeeExt(EmployeeExtReq employeeExtReq) {
       String jsonParams = JsonUtil.objectToJson(employeeExtReq);
       System.out.println("请求json: " + jsonParams);

       // 获取请求头
       Map<String, String> headerMap = this.getHeaderMap(EmployeeExtURL);

       ApiRequest request = new ApiRequest(this.domain + EmployeeExtURL, headerMap, jsonParams);
       String body = request.doRequest();
       RespBase<?> respBase = JsonUtil.jsonToObject(body, RespBase.class);
       return (RespBase<Void>) respBase;
   }

   /**
    * 批量获取考勤数据
    *
    * @param checkInReq 请求参数
    * @return 请求结果
    */
   public RespBase<KqDataResp> cloudAppKqData(CheckInReq checkInReq) {
       String jsonParams = JsonUtil.objectToJson(checkInReq);
       System.out.println("请求json: " + jsonParams);

       // 获取请求头
       Map<String, String> headerMap = this.getHeaderMap(CloudAppApiURL);
       headerMap.put("Api-Module", "KQ");
       headerMap.put("Api-Cmd", "checkin_query");

       ApiRequest request = new ApiRequest(this.domain + CloudAppApiURL, headerMap, jsonParams);
       String body = request.doRequest();
       RespBase<KqDataResp> respBase = JsonUtil.jsonToObject(body, new TypeReference<RespBase<KqDataResp>>() {});
       return respBase;
   }

   /**
    * 构造请求头
    *
    * @param requestPath 请求路径
    * @return 请求头
    */
   private Map<String, String> getHeaderMap(final String requestPath) {
       // 获取13位时间戳
       String timeStamp = TimeUtil.getTimestampMills();
       /* 获取MD5码 */
       String md5 = Encode.encodeByMD5(requestPath + timeStamp + APP_KEY + APP_SECRET);
       // 构造请求头参数
       Map<String, String> headerMap = new HashMap<>(8);
       headerMap.put("App-Key", APP_KEY);
       headerMap.put("App-Timestamp", timeStamp);
       headerMap.put("App-Sig", md5);
       return headerMap;
   }
}

3)工具类

package util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Map;

/**
 * 序列化工具类
 */
public class JsonUtil {

    private JsonUtil() {
    }

    private static final ObjectMapper MAPPER = new ObjectMapper();

    public static String mapToJson(Map<?, ?> map) {
        try {
            return MAPPER.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static <T> T jsonToObject(String json, Class<T> clazz) {
        try {
            return MAPPER.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static <T> String objectToJson(T data) {
        try {
            return MAPPER.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T jsonToObject(String json, TypeReference<T> reference) {
        try {
            return MAPPER.readValue(json, reference);
        } catch (JsonProcessingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

}

4)时间工具类

package util;


import java.util.Calendar;

public class TimeUtil {

    private TimeUtil() {
    }

    /**
     * 获取时间戳字符串
     *
     * @return 毫秒时间戳字符串
     */
    public static String getTimestampMills() {
        return String.valueOf(Calendar.getInstance().getTimeInMillis());
    }

}

5)编码工具类

package util;

import java.security.MessageDigest;

/**
 * 编码工具类
 */
public class Encode {

    private static final char[] HEX_DIGITS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);

        for (byte aByte : bytes) {
            buf.append(HEX_DIGITS[aByte >> 4 & 15]);
            buf.append(HEX_DIGITS[aByte & 15]);
        }

        return buf.toString();
    }

    public static String encode(String algorithm, String str) {
        if (str == null) {
            return null;
        } else {
            try {
                MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
                messageDigest.update(str.getBytes());
                return getFormattedText(messageDigest.digest());
            } catch (Exception var3) {
                throw new RuntimeException(var3);
            }
        }
    }

    public static String encodeByMD5(String str) {
        return encode("MD5", str);
    }
}

先到这里,以后再更

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值