lc/lc123/cloud/app/plugin/utils/FWRestfulUtils.java

317 lines
13 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 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<String,Object> 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<String,Object> 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<String,Object> datas = JSONUtil.parseObj(data);
//ECOLOGY返回的token
String token = StrUtil.nullToEmpty((String) datas.get("token"));
return token;
}
/**
* 第三步:
* 调用ecology系统的rest接口请求头部带上token和用户标识认证信息
*
* @param address ecology系统地址
* @param api rest api 接口地址(该测试代码仅支持GET请求)
* @param jsonParams 请求参数json串
*
* 注意ECOLOGY系统所有POST接口调用请求头请设置 "Content-Type","application/x-www-form-urlencoded; charset=utf-8"
*/
public static String testRestful(String address,String api,String jsonParams){
// String spk = SYSTEM_CACHE.get("SERVER_PUBLIC_KEY");
// //封装请求头参数
// RSA rsa = new RSA(null,spk);
// //对用户信息进行加密传输,暂仅支持传输OA用户ID
// String encryptUserid = rsa.encryptBase64("1",CharsetUtil.CHARSET_UTF_8,KeyType.PublicKey);
// System.out.println("encryptUserid()"+encryptUserid);
//
// //调用ECOLOGY系统接口
// String data = HttpRequest.get(address + api)
// .header("appid",APPID)
// .header("token",token)
// .header("userid",encryptUserid)
// .body(jsonParams)
// .execute().body();
// System.out.println("testRestful()"+data);
return null;
}
/**
*restful接口调用案例
*以getModeDataPageList为例
*/
public String doAction(String url, JSONObject mainTable, String fwuserid){
CloseableHttpResponse response;// 响应类,
CloseableHttpClient httpClient = HttpClients.createDefault();
//restful接口url
HttpPost httpPost = new HttpPost(FW_Main_URL + url);
//当前日期
String currentDate = getCurrentDate();
//当前时间
String currentTime = getCurrentTime();
//获取时间戳
String currentTimeTamp = getTimestamp();
Map<String, Object> params = new HashMap<>();
Map<String, Object> dataParam = new HashMap<>();
Map<String, Object> datajson = new HashMap<>();
//header
Map<String, Object> header = new HashMap<>();
header.put("systemid", FW_systemid);
header.put("currentDateTime", currentTimeTamp);
String md5Source = FW_systemid + FW_password + currentTimeTamp;
String md5OfStr = getMD5Str(md5Source).toLowerCase();
//Md5是系统标识+密码+时间戳 并且md5加密的结果
header.put("Md5",md5OfStr);
//封装mainTable参数
dataParam.put("mainTable",mainTable);
//封装operationinfo参数
JSONObject operationinfo = new JSONObject();
operationinfo.put("operator", fwuserid);
dataParam.put("operationinfo",operationinfo);
System.out.println("===请求参数dataparam==="+dataParam);
params.put("data",dataParam);
Map<String, Object>[] arr = new Map[1];
arr[0] = dataParam;
datajson.put("header", header);
datajson.put("data", arr);
//装填参数
List<BasicNameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("datajson", JSON.toJSONString(datajson)));
try{
httpPost.addHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
response = httpClient.execute(httpPost);
if (response != null && response.getEntity() != null) {
//返回信息
String resulString = EntityUtils.toString(response.getEntity());
System.out.println("成功"+ resulString);
return resulString;
}else{
System.out.println("获取数据失败,请查看日志"+currentDate+" "+currentTime);
}
}catch (Exception e){
System.out.println("请求失败"+currentDate+" "+currentTime+"====errormsg:"+e.getMessage());
}
return null;
}
public String doBillAction(String url, JSONArray mainData, JSONArray detailData, String requestName, String workflowid){
Map<String, Object> 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();
//restful接口url
HttpPost httpPost = new HttpPost("http://180.166.208.42:8043/" + "api/workflow/paService/doCreateRequest");
//当前日期
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);
//装填参数
List<BasicNameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("mainData", JSON.toJSONString(mainData)));
list.add(new BasicNameValuePair("detailData", JSON.toJSONString(detailData)));
list.add(new BasicNameValuePair("requestName", requestName));
list.add(new BasicNameValuePair("workflowId", workflowid));
try{
httpPost.addHeader("appid",FW_appid);
httpPost.addHeader("token",token);
httpPost.addHeader("userid",encryptUserid);
// httpPost.addHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
response = httpClient.execute(httpPost);
if (response != null && response.getEntity() != null) {
//返回信息
String resulString = EntityUtils.toString(response.getEntity());
System.out.println("成功"+ resulString);
return resulString;
}else{
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();
}
}