package tqq9.lc123.cloud.app.plugin.utils; import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.crypto.asymmetric.KeyType; import cn.hutool.crypto.asymmetric.RSA; import cn.hutool.http.HttpRequest; import cn.hutool.json.JSONUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import kd.bos.dataentity.OperateOption; import kd.bos.dataentity.entity.DynamicObject; import kd.bos.servicehelper.BusinessDataServiceHelper; import kd.bos.servicehelper.operation.OperationServiceHelper; import org.apache.commons.lang3.StringUtils; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; 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.EntityUtils; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.Timestamp; import java.util.*; public class FWRestfulUtils { private static final String FW_Main_URL = ConfigUtils.getThirdConfigByNumber("FW_Main_URL");//获取泛微接口ip、端口号 private static final String FW_systemid = ConfigUtils.getThirdConfigByNumber("FW_systemid");//获取泛微接口授权用户名、系统标识 private static final String FW_password = ConfigUtils.getThirdConfigByNumber("FW_password");//获取泛微接口授权密码 private static final String FW_appid = ConfigUtils.getThirdConfigByNumber("FW_appid");//FW_appid /** * 第一步: * 调用ecology注册接口,根据appid进行注册,将返回服务端公钥和Secret信息 */ public static Map regist(){ //获取当前系统RSA加密的公钥 RSA rsa = new RSA(); String publicKey = rsa.getPublicKeyBase64(); String privateKey = rsa.getPrivateKeyBase64(); //调用ECOLOGY系统接口进行注册 String data = HttpRequest.post( "http://180.166.208.42:8043/" + "api/ec/dev/auth/regist") .header("appid",FW_appid) .header("cpk",publicKey) .timeout(2000) .execute().body(); // 打印ECOLOGY响应信息 System.out.println("testRegist():"+data); Map datas = JSONUtil.parseObj(data); return datas; } /** * 第二步: * 通过第一步中注册系统返回信息进行获取token信息 */ public static String getoken(String spk, String secret){ // 公钥加密,所以RSA对象私钥为null RSA rsa = new RSA(null,spk); //对秘钥进行加密传输,防止篡改数据 String encryptSecret = rsa.encryptBase64(secret,CharsetUtil.CHARSET_UTF_8,KeyType.PublicKey); //调用ECOLOGY系统接口进行注册 String data = HttpRequest.post("http://180.166.208.42:8043/" + "api/ec/dev/auth/applytoken") .header("appid",FW_appid) .header("secret",encryptSecret) .header("time","3600") .execute().body(); System.out.println("testGetoken():"+data); Map datas = JSONUtil.parseObj(data); //ECOLOGY返回的token String token = StrUtil.nullToEmpty((String) datas.get("token")); return token; } /** *restful接口调用案例 *以getModeDataPageList为例 */ public String doAction(String url, JSONObject mainTable, String fwuserid, String requestName, String billno){ CloseableHttpResponse response;// 响应类, CloseableHttpClient httpClient = HttpClients.createDefault(); //restful接口url url = FW_Main_URL + url; HttpPost httpPost = new HttpPost(url); //当前日期 String currentDate = getCurrentDate(); //当前时间 String currentTime = getCurrentTime(); //获取时间戳 String currentTimeTamp = getTimestamp(); //header Map header = new HashMap<>(); header.put("systemid", FW_systemid); header.put("currentDateTime", currentTimeTamp); //Md5是:系统标识+密码+时间戳 并且md5加密的结果 String md5Source = FW_systemid + FW_password + currentTimeTamp; String md5OfStr = getMD5Str(md5Source).toLowerCase(); header.put("Md5",md5OfStr); //封装mainTable参数 Map dataParam = new HashMap<>(); dataParam.put("mainTable",mainTable); //封装operationinfo参数 JSONObject operationinfo = new JSONObject(); operationinfo.put("operator", fwuserid); dataParam.put("operationinfo",operationinfo); System.out.println("===请求参数dataparam==="+dataParam); Map params = new HashMap<>(); params.put("data",dataParam); Map[] arr = new Map[1]; arr[0] = dataParam; Map datajson = new HashMap<>(); datajson.put("header", header); datajson.put("data", arr); //装填参数 List list = new ArrayList<>(); list.add(new BasicNameValuePair("datajson", JSON.toJSONString(datajson))); DynamicObject pushlog = BusinessDataServiceHelper.newDynamicObject("tqq9_fwpushlog"); pushlog.set("name", requestName); pushlog.set("tqq9_billno", billno); pushlog.set("tqq9_url", url); pushlog.set("tqq9_header_tag", JSON.toJSONString(header)); pushlog.set("tqq9_body_tag", JSON.toJSONString(list)); pushlog.set("enable", "1"); pushlog.set("status", "C"); try{ httpPost.addHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8"); httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8")); response = httpClient.execute(httpPost); pushlog.set("tqq9_returnstring_tag", response.toString()); if (response != null && response.getEntity() != null) { //返回信息 String resulString = EntityUtils.toString(response.getEntity()); System.out.println("成功"+ resulString); OperationServiceHelper.executeOperate("save", "tqq9_fwpushlog", new DynamicObject[]{pushlog}, OperateOption.create()); return resulString; }else{ pushlog.set("tqq9_returnstring_tag", response.toString()); OperationServiceHelper.executeOperate("save", "tqq9_fwpushlog", new DynamicObject[]{pushlog}, OperateOption.create()); System.out.println("获取数据失败,请查看日志"+currentDate+" "+currentTime); } }catch (Exception e){ System.out.println("请求失败"+currentDate+" "+currentTime+"====errormsg:"+e.getMessage()); } return null; } /** * 调用泛微流程接口 * @param mainData * @param detailData * @param requestName * @param workflowid * @param billno * @return */ public String doBillAction(JSONArray mainData, JSONArray detailData, String requestName, String workflowid, String billno, String requestId){ Map registMap = regist(); if(registMap != null && registMap.size() > 0){ String spk = StrUtil.nullToEmpty((String) registMap.get("spk")); String secrit = StrUtil.nullToEmpty((String) registMap.get("secrit")); if(StringUtils.isNotBlank(spk) && StringUtils.isNotBlank(secrit)){ String token = getoken(spk, secrit); if(StringUtils.isNotBlank(token)){ CloseableHttpResponse response;// 响应类, CloseableHttpClient httpClient = HttpClients.createDefault(); //装填参数 List list = new ArrayList<>(); list.add(new BasicNameValuePair("mainData", JSON.toJSONString(mainData))); list.add(new BasicNameValuePair("detailData", JSON.toJSONString(detailData))); //restful接口url String url = "http://180.166.208.42:8043/"; if(StringUtils.isNotBlank(requestId)){ url = url + "api/workflow/paService/submitRequest"; list.add(new BasicNameValuePair("requestId", requestId)); }else{ url = url + "api/workflow/paService/doCreateRequest"; list.add(new BasicNameValuePair("requestName", requestName)); list.add(new BasicNameValuePair("workflowId", workflowid)); } HttpPost httpPost = new HttpPost(url); //当前日期 String currentDate = getCurrentDate(); //当前时间 String currentTime = getCurrentTime(); //封装请求头参数 RSA rsa = new RSA(null,spk); //对用户信息进行加密传输,暂仅支持传输OA用户ID String encryptUserid = rsa.encryptBase64("363", CharsetUtil.CHARSET_UTF_8, KeyType.PublicKey); DynamicObject pushlog = BusinessDataServiceHelper.newDynamicObject("tqq9_fwpushlog"); pushlog.set("name", requestName); pushlog.set("tqq9_billno", billno); pushlog.set("tqq9_url", url); pushlog.set("tqq9_header_tag", "appid:"+FW_appid+";token:"+token+";userid:"+encryptUserid); pushlog.set("tqq9_body_tag", JSON.toJSONString(list)); pushlog.set("enable", "1"); pushlog.set("status", "C"); try{ httpPost.addHeader("appid",FW_appid); httpPost.addHeader("token",token); httpPost.addHeader("userid",encryptUserid); httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8")); response = httpClient.execute(httpPost); if (response != null && response.getEntity() != null) { //返回信息 String resulString = EntityUtils.toString(response.getEntity()); pushlog.set("tqq9_returnstring_tag", resulString); System.out.println("成功"+ resulString); OperationServiceHelper.executeOperate("save", "tqq9_fwpushlog", new DynamicObject[]{pushlog}, OperateOption.create()); return resulString; }else{ pushlog.set("tqq9_returnstring_tag", response.toString()); OperationServiceHelper.executeOperate("save", "tqq9_fwpushlog", new DynamicObject[]{pushlog}, OperateOption.create()); System.out.println("获取数据失败,请查看日志"+currentDate+" "+currentTime); } }catch (Exception e){ System.out.println("请求失败"+currentDate+" "+currentTime+"====errormsg:"+e.getMessage()); } } } } return null; } public String getMD5Str(String plainText){ //定义一个字节数组 byte[] secretBytes = null; try { // 生成一个MD5加密计算摘要 MessageDigest md = MessageDigest.getInstance("MD5"); //对字符串进行加密 md.update(plainText.getBytes()); //获得加密后的数据 secretBytes = md.digest(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("没有md5这个算法!"); // throw new RuntimeException(SystemEnv.getHtmlLabelName(517545,userLanguage)); } //将加密后的数据转换为16进制数字 String md5code = new BigInteger(1, secretBytes).toString(16); // 如果生成数字未满32位,需要前面补0 // 不能把变量放到循环条件,值改变之后会导致条件变化。如果生成30位 只能生成31位md5 int tempIndex = 32 - md5code.length(); for (int i = 0; i < tempIndex; i++) { md5code = "0" + md5code; } return md5code; } public static String getCurrentTime() { Date newdate = new Date(); long datetime = newdate.getTime(); Timestamp timestamp = new Timestamp(datetime); String currenttime = (timestamp.toString()).substring(11, 13) + ":" + (timestamp.toString()).substring(14, 16) + ":" + (timestamp.toString()).substring(17, 19); return currenttime; } public static String getCurrentDate() { Date newdate = new Date(); long datetime = newdate.getTime(); Timestamp timestamp = new Timestamp(datetime); String currentdate = (timestamp.toString()).substring(0, 4) + "-" + (timestamp.toString()).substring(5, 7) + "-" + (timestamp.toString()).substring(8, 10); return currentdate; } /** * 获取当前日期时间。 YYYY-MM-DD HH:MM:SS * @return 当前日期时间 */ public static String getCurDateTime() { Date newdate = new Date(); long datetime = newdate.getTime(); Timestamp timestamp = new Timestamp(datetime); return (timestamp.toString()).substring(0, 19); } /** * 获取时间戳 格式如:19990101235959 * @return */ public static String getTimestamp(){ return getCurDateTime().replace("-", "").replace(":", "").replace(" ", ""); } public static int getIntValue(String v, int def) { try { return Integer.parseInt(v); } catch (Exception ex) { return def; } } public static String null2String(Object s) { return s == null ? "" : s.toString(); } }