定时回写BIP的销售订单-增加回写字段-累计出库主数量

This commit is contained in:
mzr 2025-03-24 16:50:32 +08:00
parent f7a6fca8f9
commit bd4f714e3a
1 changed files with 388 additions and 393 deletions

View File

@ -40,320 +40,319 @@ import java.util.*;
import java.util.zip.GZIPInputStream; import java.util.zip.GZIPInputStream;
public class ErpSaleOrderToBIPBackgroupWorkPlugin implements IBackgroundWorkPlugin { public class ErpSaleOrderToBIPBackgroupWorkPlugin implements IBackgroundWorkPlugin {
private HYSuperDMO superDMO = null; private HYSuperDMO superDMO = null;
private String baseUrl="https://www.tkkfbip.com"; private String baseUrl = "https://www.tkkfbip.com";
public HYSuperDMO getSuperDMO() { public HYSuperDMO getSuperDMO() {
if(superDMO == null) { if (superDMO == null) {
superDMO = new HYSuperDMO(); superDMO = new HYSuperDMO();
} }
return superDMO; return superDMO;
} }
/** /**
* 检查bip参数是否完整 * 检查bip参数是否完整
* @return *
*/ * @return
private Map<String,String> checkBipParam(){ */
private Map<String, String> checkBipParam() {
Map<String,String> map = new HashMap<String, String>(); Map<String, String> map = new HashMap<String, String>();
String strWhere=" pk_defdoclist in (select pk_defdoclist from bd_defdoclist where code='BIP-sq' and dr=0 ) and dr=0"; String strWhere = " pk_defdoclist in (select pk_defdoclist from bd_defdoclist where code='BIP-sq' and dr=0 ) and dr=0";
try { try {
DefdocVO[] defdocVOs=(DefdocVO[]) getSuperDMO().queryByWhereClause(DefdocVO.class, strWhere); DefdocVO[] defdocVOs = (DefdocVO[]) getSuperDMO().queryByWhereClause(DefdocVO.class, strWhere);
if(defdocVOs!=null&&defdocVOs.length>0) { if (defdocVOs != null && defdocVOs.length > 0) {
for (DefdocVO defdocVO : defdocVOs) { for (DefdocVO defdocVO : defdocVOs) {
map.put(defdocVO.getCode().trim(), defdocVO.getName()); map.put(defdocVO.getCode().trim(), defdocVO.getName());
} }
} }
} catch (DAOException e) { } catch (DAOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
return map; return map;
} }
@Override @Override
public PreAlertObject executeTask(BgWorkingContext arg0) throws BusinessException { public PreAlertObject executeTask(BgWorkingContext arg0) throws BusinessException {
// TODO Auto-generated method stub // TODO Auto-generated method stub
Date date = new Date(); Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateTime = dateFormat.format(date); String dateTime = dateFormat.format(date);
Map<String,String> bipParamMap= checkBipParam(); Map<String, String> bipParamMap = checkBipParam();
if(bipParamMap.isEmpty()) { if (bipParamMap.isEmpty()) {
return null; return null;
} }
baseUrl=bipParamMap.get("baseUrl"); baseUrl = bipParamMap.get("baseUrl");
Map<String,Object> userMap=arg0.getKeyMap(); Map<String, Object> userMap = arg0.getKeyMap();
String usercustcode=""; String usercustcode = "";
if(!userMap.isEmpty()) { if (!userMap.isEmpty()) {
if(userMap.get("code")!=null) { if (userMap.get("code") != null) {
usercustcode=userMap.get("code").toString(); usercustcode = userMap.get("code").toString();
} }
} }
String invoiceReceiveUrl = bipParamMap.get("contractSaleOrder");//开票申请单回传 String invoiceReceiveUrl = bipParamMap.get("contractSaleOrder");// 开票申请单回传
if(StringUtils.isEmpty(invoiceReceiveUrl)) { if (StringUtils.isEmpty(invoiceReceiveUrl)) {
return null; return null;
} }
Gson gson = new Gson(); Gson gson = new Gson();
//获取未推送合同销售订单更新的销售发票信息 // 获取未推送合同销售订单更新的销售发票信息
String sql=" select so_saleinvoice_b.cfirstbid,csaleinvoicebid from so_saleinvoice,so_saleinvoice_b where so_saleinvoice.csaleinvoiceid=so_saleinvoice_b.csaleinvoiceid and so_saleinvoice.fstatusflag=2 and nvl(so_saleinvoice_b.vbdef10,'N') in ('~','N') and nvl(so_saleinvoice.vdef13,'~') not in ('~') "; String sql = " select so_saleinvoice_b.cfirstbid,csaleinvoicebid from so_saleinvoice,so_saleinvoice_b where so_saleinvoice.csaleinvoiceid=so_saleinvoice_b.csaleinvoiceid and so_saleinvoice.fstatusflag=2 and nvl(so_saleinvoice_b.vbdef10,'N') in ('~','N') and nvl(so_saleinvoice.vdef13,'~') not in ('~') ";
List<Map<String,String>> l_pk = (List<Map<String, String>>)new BaseDAO().executeQuery(sql.toString(),new MapListProcessor()); List<Map<String, String>> l_pk = (List<Map<String, String>>) new BaseDAO().executeQuery(sql.toString(), new MapListProcessor());
if(l_pk.isEmpty()) { if (l_pk.isEmpty()) {
return null; return null;
} }
for (Map<String, String> map : l_pk) { for (Map<String, String> map : l_pk) {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
sb.append(" select so_saleinvoice_b.csaleinvoicebid,so_saleorder.vdef9,so_saleorder_b.vbdef11,so_saleorder_exe.ntotalarmny as totalaccrued ,so_saleorder_exe.ntotalinvoicenum as billqty "); sb.append(" select so_saleinvoice_b.csaleinvoicebid,so_saleorder.vdef9,so_saleorder_b.vbdef11,so_saleorder_exe.ntotalarmny as totalaccrued ,so_saleorder_exe.ntotalinvoicenum as billqty, NVL(so_saleorder_exe.ntotaloutnum, 0) as totaloutqty ");
sb.append(" from so_saleorder_exe,so_saleinvoice_b,so_saleinvoice,so_saleorder_b,so_saleorder "); sb.append(" from so_saleorder_exe,so_saleinvoice_b,so_saleinvoice,so_saleorder_b,so_saleorder ");
sb.append(" where so_saleorder_exe.csaleorderbid=so_saleinvoice_b.csrcbid "); sb.append(" where so_saleorder_exe.csaleorderbid=so_saleinvoice_b.csrcbid ");
sb.append(" and so_saleinvoice.csaleinvoiceid=so_saleinvoice_b.csaleinvoiceid and so_saleinvoice.fstatusflag=2 "); sb.append(" and so_saleinvoice.csaleinvoiceid=so_saleinvoice_b.csaleinvoiceid and so_saleinvoice.fstatusflag=2 ");
sb.append(" and so_saleorder_exe.csaleorderbid=so_saleorder_b.csaleorderbid "); sb.append(" and so_saleorder_exe.csaleorderbid=so_saleorder_b.csaleorderbid ");
sb.append(" and so_saleorder.csaleorderid=so_saleorder_b.csaleorderid "); sb.append(" and so_saleorder.csaleorderid=so_saleorder_b.csaleorderid ");
sb.append(" and so_saleorder_exe.dr=0 and so_saleorder.dr=0 and so_saleorder_b.dr=0 "); sb.append(" and so_saleorder_exe.dr=0 and so_saleorder.dr=0 and so_saleorder_b.dr=0 ");
sb.append(" and nvl(so_saleorder.vdef9,'~') not in ('~') "); sb.append(" and nvl(so_saleorder.vdef9,'~') not in ('~') ");
sb.append(" and so_saleorder_exe.csaleorderbid='").append(map.get("cfirstbid")).append("'"); sb.append(" and so_saleorder_exe.csaleorderbid='").append(map.get("cfirstbid")).append("'");
List<Map<String,String>> ll_saleorder = (List<Map<String, String>>)new BaseDAO().executeQuery(sb.toString(),new MapListProcessor()); List<Map<String, String>> ll_saleorder = (List<Map<String, String>>) new BaseDAO().executeQuery(sb.toString(), new MapListProcessor());
if(ll_saleorder.isEmpty()) { if (ll_saleorder.isEmpty()) {
continue; continue;
} }
try { try {
String accessToken=getAccessToken(baseUrl,bipParamMap); String accessToken = getAccessToken(baseUrl, bipParamMap);
Map<String,String> tokenParam = new HashMap<>(); Map<String, String> tokenParam = new HashMap<>();
tokenParam.put("access_token", accessToken); tokenParam.put("access_token", accessToken);
Map<String, String> headers = new HashMap<String, String>(); Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json"); headers.put("Content-Type", "application/json");
String custUpdateUrl=baseUrl+invoiceReceiveUrl; String custUpdateUrl = baseUrl + invoiceReceiveUrl;
if(accessToken!="") { if (accessToken != "") {
JSONObject js_apct_detail =new JSONObject(); JSONObject js_apct_detail = new JSONObject();
JSONObject js_apct =new JSONObject(); JSONObject js_apct = new JSONObject();
String hid=ll_saleorder.get(0).get("vdef9");//BIP合同销售订单更新 主表id String hid = ll_saleorder.get(0).get("vdef9");// BIP合同销售订单更新 主表id
List<Map<String,Object>> l_map_f = new ArrayList<Map<String,Object>>(); List<Map<String, Object>> l_map_f = new ArrayList<Map<String, Object>>();
for (Map<String, String> custpkmap : ll_saleorder) { for (Map<String, String> custpkmap : ll_saleorder) {
Map<String, Object> b_map = new HashMap<String, Object>(); Map<String, Object> b_map = new HashMap<String, Object>();
b_map.put("id", custpkmap.get("vbdef11"));//BIP合同销售订单更新 子表id b_map.put("id", custpkmap.get("vbdef11"));// BIP合同销售订单更新 子表id
b_map.put("billQty", custpkmap.get("billqty"));//累计开票主数量 b_map.put("billQty", custpkmap.get("billqty"));// 累计开票主数量
b_map.put("totalAccrued", custpkmap.get("totalaccrued"));//累计确认应收金额 b_map.put("totalAccrued", custpkmap.get("totalaccrued"));// 累计确认应收金额
b_map.put("totalOutQty", custpkmap.get("totaloutqty"));// 累计出库主数量
l_map_f.add(b_map); l_map_f.add(b_map);
js_apct.put("contractOrdersList", l_map_f); js_apct.put("contractOrdersList", l_map_f);
js_apct.put("id", hid); js_apct.put("id", hid);
js_apct_detail.put("HTXSDD", js_apct); js_apct_detail.put("HTXSDD", js_apct);
String resultString=doSendHttp(custUpdateUrl,"POST",tokenParam,"",headers, js_apct_detail.toJSONString()); String resultString = doSendHttp(custUpdateUrl, "POST", tokenParam, "", headers, js_apct_detail.toJSONString());
Map updateMap = gson.fromJson(resultString, Map.class); Map updateMap = gson.fromJson(resultString, Map.class);
String updateSql=""; String updateSql = "";
if (StringUtils.equals("200", updateMap.get("code").toString())) {//保存更新成功后需要更新日志表 if (StringUtils.equals("200", updateMap.get("code").toString())) {// 保存更新成功后需要更新日志表
updateSql="update so_saleinvoice_b set vbdef10='Y' where csaleinvoiceid='"+map.get("csaleinvoicebid")+"'"; updateSql = "update so_saleinvoice_b set vbdef10='Y' where csaleinvoiceid='" + map.get("csaleinvoicebid") + "'";
}else { } else {
updateSql="update so_saleinvoice_b set vbdef10='N' where csaleinvoiceid='"+map.get("csaleinvoicebid")+"'"; updateSql = "update so_saleinvoice_b set vbdef10='N' where csaleinvoiceid='" + map.get("csaleinvoicebid") + "'";
} }
getSuperDMO().executeUpdateSQL(updateSql); getSuperDMO().executeUpdateSQL(updateSql);
} }
} }
} catch (InvalidKeyException e) { } catch (InvalidKeyException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
}//获取BIP的token }// 获取BIP的token
catch (SQLException e) { catch (SQLException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
}
} return null;
}
return null; /**
} * 查询bip 中开户行及银行类型id
*
* @param map
* @param bipUrl
* @return
*/
private static Map<String, String> getBIPBankID(HashMap<String, String> map, String bipUrl, String accessToken, String bankdocname) {
Gson gson = new Gson();
Map<String, String> tokenParam = new HashMap<>();
/** tokenParam.put("access_token", accessToken);
* 查询bip 中开户行及银行类型id String jsonData = JSON.toJSONString(map);
* @param map String resultString = doSendHttp(bipUrl, "POST", tokenParam, "", new HashMap<>(), jsonData);
* @param bipUrl
* @return
*/
private static Map<String,String> getBIPBankID(HashMap<String, String> map,String bipUrl,String accessToken,String bankdocname) {
Gson gson = new Gson();
Map<String,String> tokenParam = new HashMap<>();
tokenParam.put("access_token", accessToken);
String jsonData= JSON.toJSONString(map);
String resultString=doSendHttp(bipUrl,"POST",tokenParam,"",new HashMap<>(), jsonData);
// Map custDetailresult = gson.fromJson(resultString, Map.class); // Map custDetailresult = gson.fromJson(resultString, Map.class);
JSONObject custDetailresult= JSON.parseObject(resultString); JSONObject custDetailresult = JSON.parseObject(resultString);
if (StringUtils.equals("200", custDetailresult.get("code").toString())) {//数据存在 if (StringUtils.equals("200", custDetailresult.get("code").toString())) {// 数据存在
Map<String, Object> dataInfo = (Map<String, Object>)custDetailresult.get("data"); Map<String, Object> dataInfo = (Map<String, Object>) custDetailresult.get("data");
if(!MMValueCheck.isEmpty(dataInfo.get("recordList"))){ if (!MMValueCheck.isEmpty(dataInfo.get("recordList"))) {
List<Map<String,String>> l_record=(List<Map<String, String>>) dataInfo.get("recordList"); List<Map<String, String>> l_record = (List<Map<String, String>>) dataInfo.get("recordList");
return l_record.get(0); return l_record.get(0);
}else { } else {
map.remove("linenumber"); map.remove("linenumber");
map.put("name", bankdocname); map.put("name", bankdocname);
jsonData= JSON.toJSONString(map); jsonData = JSON.toJSONString(map);
resultString=doSendHttp(bipUrl,"POST",tokenParam,"",new HashMap<>(), jsonData); resultString = doSendHttp(bipUrl, "POST", tokenParam, "", new HashMap<>(), jsonData);
// custDetailresult = gson.fromJson(resultString, Map.class); // custDetailresult = gson.fromJson(resultString, Map.class);
custDetailresult= JSON.parseObject(resultString); custDetailresult = JSON.parseObject(resultString);
if (StringUtils.equals("200", custDetailresult.get("code").toString())) {//数据存在 if (StringUtils.equals("200", custDetailresult.get("code").toString())) {// 数据存在
dataInfo = (Map<String, Object>)custDetailresult.get("data"); dataInfo = (Map<String, Object>) custDetailresult.get("data");
if(!MMValueCheck.isEmpty(dataInfo.get("recordList"))){ if (!MMValueCheck.isEmpty(dataInfo.get("recordList"))) {
List<Map<String,String>> l_record=(List<Map<String, String>>) dataInfo.get("recordList"); List<Map<String, String>> l_record = (List<Map<String, String>>) dataInfo.get("recordList");
return l_record.get(0); return l_record.get(0);
} }
} }
} }
} }
return null; return null;
} }
public static String doSendHttp(String baseUrl, String method, Map<String, String> paramMap, String mediaType, Map<String, String> headers, String json){ public static String doSendHttp(String baseUrl, String method, Map<String, String> paramMap, String mediaType, Map<String, String> headers, String json) {
HttpURLConnection urlConnection = null; HttpURLConnection urlConnection = null;
InputStream in = null; InputStream in = null;
OutputStream out = null; OutputStream out = null;
BufferedReader bufferedReader = null; BufferedReader bufferedReader = null;
String result = null; String result = null;
try { try {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
sb.append(baseUrl); sb.append(baseUrl);
if(paramMap != null){ if (paramMap != null) {
sb.append("?"); sb.append("?");
for (Map.Entry<String, String> entry : paramMap.entrySet()){ for (Map.Entry<String, String> entry : paramMap.entrySet()) {
String key = entry.getKey(); String key = entry.getKey();
String value = entry.getValue(); String value = entry.getValue();
sb.append(key + "="+ value).append("&"); sb.append(key + "=" + value).append("&");
baseUrl = sb.toString().substring(0,sb.toString().length()- 1); baseUrl = sb.toString().substring(0, sb.toString().length() - 1);
} }
} }
// log.error("uRL:" + baseUrl); // log.error("uRL:" + baseUrl);
// // ´òÓ¡ÇëÇóURLºÍ·½·¨ // // ´òÓ¡ÇëÇóURLºÍ·½·¨
// log.error("Request URL: " + baseUrl); // log.error("Request URL: " + baseUrl);
// log.error("Request Method: " + method); // log.error("Request Method: " + method);
URL urlobj = new URL(baseUrl); URL urlobj = new URL(baseUrl);
if("https".equalsIgnoreCase(urlobj.getProtocol())) {//判定网址是否信任不信任则调用忽略信任工具类SslUtil if ("https".equalsIgnoreCase(urlobj.getProtocol())) {// 判定网址是否信任不信任则调用忽略信任工具类SslUtil
IgnoreSslUtil.ignoreSsl(); IgnoreSslUtil.ignoreSsl();
} }
urlConnection = (HttpURLConnection)urlobj.openConnection(); urlConnection = (HttpURLConnection) urlobj.openConnection();
urlConnection.setConnectTimeout(50000); urlConnection.setConnectTimeout(50000);
urlConnection.setRequestMethod(method); urlConnection.setRequestMethod(method);
urlConnection.setDoInput(true); urlConnection.setDoInput(true);
urlConnection.setUseCaches(false); urlConnection.setUseCaches(false);
// 如果设置了自定义头则打印它们 // 如果设置了自定义头则打印它们
if (headers != null && !headers.isEmpty()) { if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, String> entry : headers.entrySet()) { for (Map.Entry<String, String> entry : headers.entrySet()) {
urlConnection.addRequestProperty(entry.getKey(), entry.getValue()); urlConnection.addRequestProperty(entry.getKey(), entry.getValue());
// log.error("Request Header: " + entry.getKey() + ": " + entry.getValue()); // log.error("Request Header: " + entry.getKey() + ": " + entry.getValue());
} }
} }
if(json !=null&&json.length()>0){ if (json != null && json.length() > 0) {
// log.error("Request Body: " + json); // log.error("Request Body: " + json);
urlConnection.setDoInput(true); urlConnection.setDoInput(true);
urlConnection.setDoOutput(true); urlConnection.setDoOutput(true);
out=urlConnection.getOutputStream(); out = urlConnection.getOutputStream();
out.write(json.getBytes("utf-8")); out.write(json.getBytes("utf-8"));
out.flush(); out.flush();
} }
int resCode=urlConnection.getResponseCode(); int resCode = urlConnection.getResponseCode();
String ecod=urlConnection.getContentEncoding(); String ecod = urlConnection.getContentEncoding();
if(resCode==HttpURLConnection.HTTP_OK||resCode== HttpURLConnection.HTTP_CREATED if (resCode == HttpURLConnection.HTTP_OK || resCode == HttpURLConnection.HTTP_CREATED
||resCode==HttpURLConnection.HTTP_ACCEPTED){ || resCode == HttpURLConnection.HTTP_ACCEPTED) {
if(StringUtils.isNotEmpty(ecod)&&ecod.equals("gzip")) { if (StringUtils.isNotEmpty(ecod) && ecod.equals("gzip")) {
in=new GZIPInputStream(urlConnection.getInputStream()); in = new GZIPInputStream(urlConnection.getInputStream());
}else{ } else {
in=urlConnection.getInputStream(); in = urlConnection.getInputStream();
} }
}else { } else {
in=urlConnection.getErrorStream(); in = urlConnection.getErrorStream();
} }
bufferedReader =new BufferedReader(new InputStreamReader(in,"utf-8")); bufferedReader = new BufferedReader(new InputStreamReader(in, "utf-8"));
StringBuffer temp=new StringBuffer(); StringBuffer temp = new StringBuffer();
String line=bufferedReader.readLine(); String line = bufferedReader.readLine();
while (line!=null){ while (line != null) {
temp.append(line).append("\r\n"); temp.append(line).append("\r\n");
line=bufferedReader.readLine(); line = bufferedReader.readLine();
} }
if(ecod==null||ecod.equals("gzip")){ if (ecod == null || ecod.equals("gzip")) {
ecod= Charset.forName("utf-8").name(); ecod = Charset.forName("utf-8").name();
} }
result=new String(temp.toString().getBytes("utf-8"),ecod); result = new String(temp.toString().getBytes("utf-8"), ecod);
}catch(Exception e) { } catch (Exception e) {
JSONObject js=new JSONObject(); JSONObject js = new JSONObject();
js.put("",-1); js.put("", -1);
js.put("message","调用外系统接口失败:"+e.getMessage()); js.put("message", "调用外系统接口失败:" + e.getMessage());
result=js.toString(); result = js.toString();
e.printStackTrace(); e.printStackTrace();
}finally { } finally {
if(null!=bufferedReader) { if (null != bufferedReader) {
try{ try {
bufferedReader.close(); bufferedReader.close();
}catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
if(null!=out) { if (null != out) {
try{ try {
out.close(); out.close();
}catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
if(null!=in) { if (null != in) {
try{ try {
in.close(); in.close();
}catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
urlConnection.disconnect(); urlConnection.disconnect();
} }
return result; return result;
} }
// private String createCustBankMap(Map<String,String> map,String access_token) { // private String createCustBankMap(Map<String,String> map,String access_token) {
@ -400,151 +399,150 @@ public class ErpSaleOrderToBIPBackgroupWorkPlugin implements IBackgroundWorkPlug
// } // }
private String getAccessToken(String baseUrl,Map<String,String> bipParamMap) throws NoSuchAlgorithmException, InvalidKeyException, IOException { private String getAccessToken(String baseUrl, Map<String, String> bipParamMap) throws NoSuchAlgorithmException, InvalidKeyException, IOException {
String tokenUrl=baseUrl+"/iuap-api-auth/open-auth/selfAppAuth/getAccessToken"; String tokenUrl = baseUrl + "/iuap-api-auth/open-auth/selfAppAuth/getAccessToken";
// String appKey = "f10c4bf17b1d4e1fb08eb82bf8540eab"; // String appKey = "f10c4bf17b1d4e1fb08eb82bf8540eab";
String appKey = bipParamMap.get("appKey"); String appKey = bipParamMap.get("appKey");
// String appSecret = "71dc2a58ca378c1a1143231a62e73e75a60e9236"; // String appSecret = "71dc2a58ca378c1a1143231a62e73e75a60e9236";
String appSecret = bipParamMap.get("appSecret"); String appSecret = bipParamMap.get("appSecret");
String accessToken=""; String accessToken = "";
Map<String, String> params = new HashMap<>(); Map<String, String> params = new HashMap<>();
params.put("appKey", appKey); params.put("appKey", appKey);
String timestamp = String.valueOf(System.currentTimeMillis()); String timestamp = String.valueOf(System.currentTimeMillis());
params.put("timestamp", timestamp); params.put("timestamp", timestamp);
// 计算签名 // 计算签名
Map<String, String> treeMap; Map<String, String> treeMap;
if (params instanceof TreeMap) { if (params instanceof TreeMap) {
treeMap = params; treeMap = params;
} else { } else {
treeMap = new TreeMap<>(params); treeMap = new TreeMap<>(params);
} }
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
for (Map.Entry<String, String> entry : treeMap.entrySet()) { for (Map.Entry<String, String> entry : treeMap.entrySet()) {
stringBuilder.append(entry.getKey()).append(entry.getValue()); stringBuilder.append(entry.getKey()).append(entry.getValue());
} }
Mac mac = Mac.getInstance("HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(appSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); mac.init(new SecretKeySpec(appSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] signData = mac.doFinal(stringBuilder.toString().getBytes(StandardCharsets.UTF_8)); byte[] signData = mac.doFinal(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
String base64String = Base64.getEncoder().encodeToString(signData); String base64String = Base64.getEncoder().encodeToString(signData);
String signature = URLEncoder.encode(base64String, "UTF-8"); String signature = URLEncoder.encode(base64String, "UTF-8");
params.put("signature", signature); params.put("signature", signature);
String responseString = doGet(tokenUrl, params); String responseString = doGet(tokenUrl, params);
Gson gson = new Gson(); Gson gson = new Gson();
Map result = gson.fromJson(responseString, Map.class); Map result = gson.fromJson(responseString, Map.class);
if (StringUtils.equals("00000", result.get("code").toString())) { if (StringUtils.equals("00000", result.get("code").toString())) {
Map<String, Object> tokenInfo = (Map<String, Object>) result.get("data"); Map<String, Object> tokenInfo = (Map<String, Object>) result.get("data");
accessToken = (String) tokenInfo.get("access_token"); accessToken = (String) tokenInfo.get("access_token");
} }
return accessToken; return accessToken;
} }
private String doPost(String requestUrl, JSONObject jsonObject) throws IOException {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(500);
cm.setDefaultMaxPerRoute(50);
private String doPost(String requestUrl,JSONObject jsonObject) throws IOException { RequestConfig globalConfig = RequestConfig.custom().setConnectionRequestTimeout(5000) // 连接池获取连接超时
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); .setConnectTimeout(5000) // 连接建立超时
cm.setMaxTotal(500); .setSocketTimeout(20000) // 等待响应超时
cm.setDefaultMaxPerRoute(50); .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
RequestConfig globalConfig = RequestConfig.custom().setConnectionRequestTimeout(5000) // 连接池获取连接超时 CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm)
.setConnectTimeout(5000) // 连接建立超时 .setDefaultRequestConfig(globalConfig).build();
.setSocketTimeout(20000) // 等待响应超时 HttpPost post = new HttpPost(requestUrl);
.setCookieSpec(CookieSpecs.IGNORE_COOKIES).build(); post.setHeader("Content-Type", "application/json;charset=UTF-8");
post.setEntity(new StringEntity(JSONObject.toJSONString(jsonObject), "utf-8"));
String responseString = httpClient.execute(post, response -> EntityUtils.toString(response.getEntity()));
return responseString;
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm) }
.setDefaultRequestConfig(globalConfig).build();
HttpPost post = new HttpPost(requestUrl);
post.setHeader("Content-Type", "application/json;charset=UTF-8");
post.setEntity(new StringEntity(JSONObject.toJSONString(jsonObject), "utf-8"));
String responseString = httpClient.execute(post, response -> EntityUtils.toString(response.getEntity()));
return responseString;
}
private String doPost(String requestUrl, Map<String, Object> param) throws IOException { private String doPost(String requestUrl, Map<String, Object> param) throws IOException {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(500); cm.setMaxTotal(500);
cm.setDefaultMaxPerRoute(50); cm.setDefaultMaxPerRoute(50);
RequestConfig globalConfig = RequestConfig.custom().setConnectionRequestTimeout(5000) // 连接池获取连接超时 RequestConfig globalConfig = RequestConfig.custom().setConnectionRequestTimeout(5000) // 连接池获取连接超时
.setConnectTimeout(5000) // 连接建立超时 .setConnectTimeout(5000) // 连接建立超时
.setSocketTimeout(20000) // 等待响应超时 .setSocketTimeout(20000) // 等待响应超时
.setCookieSpec(CookieSpecs.IGNORE_COOKIES).build(); .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm) CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm)
.setDefaultRequestConfig(globalConfig).build(); .setDefaultRequestConfig(globalConfig).build();
HttpPost post = new HttpPost(requestUrl); HttpPost post = new HttpPost(requestUrl);
post.setHeader("Content-Type", "application/json;charset=UTF-8"); post.setHeader("Content-Type", "application/json;charset=UTF-8");
post.setEntity(new StringEntity(JSONObject.toJSONString(param), "utf-8")); post.setEntity(new StringEntity(JSONObject.toJSONString(param), "utf-8"));
String responseString = httpClient.execute(post, response -> EntityUtils.toString(response.getEntity())); String responseString = httpClient.execute(post, response -> EntityUtils.toString(response.getEntity()));
return responseString; return responseString;
} }
private static String doGet(String path, Map<String, String> params) throws IOException { private static String doGet(String path, Map<String, String> params) throws IOException {
HttpURLConnection conn = null; HttpURLConnection conn = null;
InputStream is = null; InputStream is = null;
BufferedReader br = null; BufferedReader br = null;
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
try { try {
if (params != null) { if (params != null) {
String paramStr = ""; String paramStr = "";
for (String key : params.keySet()) { for (String key : params.keySet()) {
if (!paramStr.isEmpty()) { if (!paramStr.isEmpty()) {
paramStr += '&'; paramStr += '&';
} }
paramStr += key + '=' + params.get(key); paramStr += key + '=' + params.get(key);
} }
if (path.indexOf('?') > 0) { if (path.indexOf('?') > 0) {
path += '&' + paramStr; path += '&' + paramStr;
} else { } else {
path += '?' + paramStr; path += '?' + paramStr;
} }
} }
//创建远程url连接对象 // 创建远程url连接对象
URL url = new URL(path); URL url = new URL(path);
if("https".equalsIgnoreCase(url.getProtocol())){//判定网址是否信任不信任则调用忽略信任工具类SslUtil if ("https".equalsIgnoreCase(url.getProtocol())) {// 判定网址是否信任不信任则调用忽略信任工具类SslUtil
IgnoreSslUtil.ignoreSsl(); IgnoreSslUtil.ignoreSsl();
} }
//通过远程url连接对象打开一个连接强转成HTTPURLConnection类 // 通过远程url连接对象打开一个连接强转成HTTPURLConnection类
conn = (HttpURLConnection) url.openConnection(); conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET"); conn.setRequestMethod("GET");
//设置连接超时时间和读取超时时间 // 设置连接超时时间和读取超时时间
conn.setConnectTimeout(120000); conn.setConnectTimeout(120000);
conn.setReadTimeout(120000); conn.setReadTimeout(120000);
conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Accept", "application/json");
//发送请求 // 发送请求
conn.connect(); conn.connect();
//通过conn取得输入流并使用Reader读取 // 通过conn取得输入流并使用Reader读取
if (200 == conn.getResponseCode()) { if (200 == conn.getResponseCode()) {
is = conn.getInputStream(); is = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8")); br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line; String line;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
result.append(line); result.append(line);
System.out.println(line); System.out.println(line);
} }
} else { } else {
System.out.println("ResponseCode is an error code:" + conn.getResponseCode()); System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
} }
} catch (MalformedURLException e) { } catch (MalformedURLException e) {
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
// finally { // finally {
// try { // try {
// if (br != null) { // if (br != null) {
@ -558,11 +556,8 @@ public class ErpSaleOrderToBIPBackgroupWorkPlugin implements IBackgroundWorkPlug
// } // }
// conn.disconnect(); // conn.disconnect();
// } // }
return result.toString(); return result.toString();
} }
// private String doGet(String requestUrl, Map<String, String> paramMap) throws IOException { // private String doGet(String requestUrl, Map<String, String> paramMap) throws IOException {