工行银企直联(dom4j无中间件版)
最近,接手了工行银企直联的任务,在网上找了很多,发现能一次说清的文章很少,此篇文章专为第一次接触银企直联的同学准备。
1、准备包:dom4j(自行百度,如果这一步都不知道怎么做,接下来的过程也就别看了)
2、逻辑
3、Http的Post方法
public static String signICBC(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "INFOSEC_SIGN/1.0");
conn.setRequestProperty("Content-Length", String.valueOf(param.length()));
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.write(param);
out.flush();
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(),"GB2312"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
@Autowired
FiveFinanceXML fiveFinanceXML;
public String postICBC(String packageId,String transCode,String xml,Boolean sign,String version,String zip){
String NCIp = "127.0.0.1";
String NCPort = "7070";
String NCPort2 = "7080";
boolean signatureflg = sign;
String retcertPath = "E:\\admin.crt";
String result = "";
try {
String sCoding = "GBK";
String cmpVersion = version;
String sZip = zip;
String sLanguage = "zh_CN";
String sPackageID = packageId;
String sTransCode = transCode;
String sBankCode = "102";
String sGroupCIS = "自己填";
String sID = "自己填";
String sContent = xml;
System.out.println(sContent);
sContentSign = sContent;
if (signatureflg) {
java.net.URL aURL = new java.net.URL("http://" + NCIp + ":" + NCPort2);
java.net.HttpURLConnection urlConnection = (java.net.HttpURLConnection) aURL.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Length",String.valueOf(sContentSign.getBytes(sCoding).length));
urlConnection.setRequestProperty("Content-Type","INFOSEC_SIGN/1.0");
BufferedOutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
out.write(sContentSign.getBytes(sCoding));
out.flush();
out.close();
int responseCode = urlConnection.getResponseCode();
if (responseCode != 200){
System.out.println("NC签名失败");
}
String resM = urlConnection.getResponseMessage();
StringBuffer repContent = new StringBuffer("");
InputStreamReader in = new InputStreamReader(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(in);
String readLine = null;
while ((readLine = bufferedReader.readLine()) != null) {
repContent.append(readLine);
}
in.close();
urlConnection.disconnect();
int beginSign = 0;
int endSign = 0;
try{
beginSign = repContent.indexOf("<sign>") + 6;
endSign = repContent.indexOf("</sign>");
System.out.println("repIndx="+beginSign+"&"+endSign);
}catch(Exception e){
System.out.println("!!!!!!!!!!接收签名数据失败,请检查nc设置!!!!!!!!!!");
}
String repSignContent = repContent.substring(beginSign, endSign);
System.out.println("签名内容:"+repSignContent);
Calendar rightNow = Calendar.getInstance();
int year = rightNow.get(Calendar.YEAR);
int month = rightNow.get(Calendar.MONTH) + 1;
int date = rightNow.get(Calendar.DAY_OF_MONTH);
int hour = rightNow.get(Calendar.HOUR_OF_DAY);
int minute = rightNow.get(Calendar.MINUTE);
int second = rightNow.get(Calendar.SECOND);
String sendTime = String.valueOf(year) + String.valueOf(month)
+ String.valueOf(date) + String.valueOf(hour)
+ String.valueOf(minute) + String.valueOf(second);
String urlStr1 = "http://" + NCIp + ":" + NCPort + "/servlet/ICBCCMPAPIReqServlet?PackageID=" + sPackageID + "&SendTime=" + sendTime;
HttpClient myclient = HttpClientBuilder.create().build();
HttpPost mypost = new HttpPost(urlStr1);
mypost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=GBK");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Version", cmpVersion));
params.add(new BasicNameValuePair("TransCode", sTransCode));
params.add(new BasicNameValuePair("BankCode", sBankCode));
params.add(new BasicNameValuePair("GroupCIS", sGroupCIS));
params.add(new BasicNameValuePair("ID", sID));
params.add(new BasicNameValuePair("PackageID", sPackageID));
params.add(new BasicNameValuePair("Cert", ""));
params.add(new BasicNameValuePair("Language", sLanguage));
params.add(new BasicNameValuePair("zipFlag", sZip));
params.add(new BasicNameValuePair("reqData", repSignContent));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
mypost.setEntity(entity);
HttpResponse response = myclient.execute(mypost);
System.out.println("开始发送到加密端..."+System.currentTimeMillis());
int returnFlag = myclient.execute(mypost).getStatusLine().getStatusCode();
System.out.println("已返回数据...");
try {
HttpEntity resEntity = response.getEntity();
String postResult = EntityUtils.toString(resEntity);
if(postResult.startsWith("reqData=")){
postResult = postResult.substring(8);
}
System.out.println("******************************NC返回******************************\n");
System.out.println(new String(postResult));
byte[] decodeResult = getFromBASE64(postResult);
String sysout = new String(decodeResult, sCoding);
int retsign = sysout.indexOf("ICBCCMP");
if (retsign != -1){
int mLength = Integer.parseInt((sysout.substring(0,10)).trim());
String message = sysout.substring(10,10+mLength);
String seperator = sysout.substring(10+mLength,10+mLength+7);
if (seperator == null || !seperator.equals("ICBCCMP")){
System.out.println("返回包分隔符错误");
}
byte[] crymessage = getFromBASE64(sysout.substring(10+mLength+7));
System.out.println("******************************银企互联返回数据******************************\n");
System.out.println(sysout);
result = sysout;
} catch (Exception e) {
e.printStackTrace();
}
mypost.releaseConnection();
}
else {
Calendar rightNow = Calendar.getInstance();
int year = rightNow.get(Calendar.YEAR);
int month = rightNow.get(Calendar.MONTH) + 1;
int date = rightNow.get(Calendar.DAY_OF_MONTH);
int hour = rightNow.get(Calendar.HOUR_OF_DAY);
int minute = rightNow.get(Calendar.MINUTE);
int second = rightNow.get(Calendar.SECOND);
String sendTime =
String.valueOf(year)
+ String.valueOf(month)
+ String.valueOf(date)
+ String.valueOf(hour)
+ String.valueOf(minute)
+ String.valueOf(second);
String urlStr = "http://"+ NCIp + ":" + NCPort + "/servlet/ICBCCMPAPIReqServlet?userId="+sID+"&PackageID=" + sPackageID + "&SendTime=" + sendTime;
System.out.println("url==" + urlStr);
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(urlStr);
post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=GBK");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Version", cmpVersion));
params.add(new BasicNameValuePair("TransCode", sTransCode));
params.add(new BasicNameValuePair("BankCode", sBankCode));
params.add(new BasicNameValuePair("GroupCIS", sGroupCIS));
params.add(new BasicNameValuePair("ID", sID));
params.add(new BasicNameValuePair("PackageID", sPackageID));
params.add(new BasicNameValuePair("Cert", ""));
params.add(new BasicNameValuePair("Language", sLanguage));
params.add(new BasicNameValuePair("reqData", sContent));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
post.setEntity(entity);
HttpResponse response = client.execute(post);
System.out.println("开始发送。。。");
int returnFlag = response.getStatusLine().getStatusCode();
System.out.println("发送成功。。。");
try {
HttpEntity resEntity = response.getEntity();
String postResult = EntityUtils.toString(resEntity);
System.out.println("******************************NC返回******************************\n");
System.out.println(new String(postResult));
if(postResult.startsWith("reqData=")){
postResult = postResult.substring(8);
System.out.println("retMessage==" + new String(postResult));
byte[] decodeResult = getFromBASE64(postResult);
String sysout = new String(decodeResult,sCoding);
System.out.println("******************************银企互联返回数据******************************\n");
System.out.println(sysout);
return sysout;
}else{
System.out.println("******************************银企互联返回数据******************************\n");
System.out.println(new String(postResult));
return new String(postResult);
}
} catch (Exception e) {
e.printStackTrace();
}
post.releaseConnection();
}
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace(System.out);
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace(System.out);
System.err.println("error:" + e.getMessage());
}
return result;
}
4、解密方法
public static byte[] getFromBASE64(String s) {
if (s == null)
return null;
BASE64Decoder decoder = new BASE64Decoder();
try {
return decoder.decodeBuffer(s);
} catch (Exception e) {
return null;
}
}
5、利用dom4j构建报文
public Document queryBanlanceICBC(String account, String packageId,Date date) {
Document document = DocumentHelper.createDocument();
document.setXMLEncoding("GBK");
Element cms = document.addElement("CMS");
Element eb = cms.addElement("eb");
Element pub = eb.addElement("pub");
Element in = eb.addElement("in");
pub.addElement("TransCode").setText("QACCBAL");
pub.addElement("CIS").setText("");
pub.addElement("BankCode").setText("102");
pub.addElement("ID").setText("");
pub.addElement("TranDate").setText(MyDateUtil.dateToStr1(date));
pub.addElement("TranTime").setText(MyDateUtil.getDateMS(date));
pub.addElement("fSeqno").setText(packageId);
in.addElement("TotalNum").setText("1");
in.addElement("BLFlag");
in.addElement("SynFlag");
Element rd = in.addElement("rd");
rd.addElement("iSeqno").setText(packageId);
rd.addElement("AccNo").setText(account);
rd.addElement("CurrType");
rd.addElement("ReqReserved3");
rd.addElement("AcctSeq");
rd.addElement("MainAcctNo");
return document;
}
6、XML与Map的转化(转载)
public Map<String, Object> Dom2Map(Document doc){
Map<String, Object> map = new HashMap<String, Object>();
if(doc == null)
return map;
Element root = doc.getRootElement();
for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
Element e = (Element) iterator.next();
List list = e.elements();
if(list.size() > 0){
map.put(e.getName(), Dom2Map(e));
}else
map.put(e.getName(), e.getText());
}
return map;
}
public Map Dom2Map(Element e){
Map map = new HashMap();
List list = e.elements();
if(list.size() > 0){
for (int i = 0;i < list.size(); i++) {
Element iter = (Element) list.get(i);
List mapList = new ArrayList();
if(iter.elements().size() > 0){
Map m = Dom2Map(iter);
if(map.get(iter.getName()) != null){
Object obj = map.get(iter.getName());
if(!obj.getClass().getName().equals("java.util.ArrayList")){
mapList = new ArrayList();
mapList.add(obj);
mapList.add(m);
}
if(obj.getClass().getName().equals("java.util.ArrayList")){
mapList = (List) obj;
mapList.add(m);
}
map.put(iter.getName(), mapList);
}else
map.put(iter.getName(), m);
}
else{
if(map.get(iter.getName()) != null){
Object obj = map.get(iter.getName());
if(!obj.getClass().getName().equals("java.util.ArrayList")){
mapList = new ArrayList();
mapList.add(obj);
mapList.add(iter.getText());
}
if(obj.getClass().getName().equals("java.util.ArrayList")){
mapList = (List) obj;
mapList.add(iter.getText());
}
map.put(iter.getName(), mapList);
}else
map.put(iter.getName(), iter.getText());
}
}
}else
map.put(e.getName(), e.getText());
return map;
}
7、发送报文
public Map queryBalanceICBC(String account, String userLogin, String uiSref) throws DocumentException {
String packageId = "2021083644858";
Date date = new Date();
String sendTime = MyDateUtil.dateToStr1(date)+MyDateUtil.getDateMS(date);
Document document = fiveFinanceXML.queryBanlanceICBC("0200004519000100173", packageId, new Date());
String transCode = "QACCBAL";
String xml = document.asXML();
Boolean sign = false;
String version = "0.0.1.0";
String sr = financeHttpPost.postICBC(packageId, transCode, xml, sign, version,"0");
Document doc = DocumentHelper.parseText(sr);
Map<String, Object> xmlMap = fiveFinanceXML.Dom2Map(doc);
Map response = (Map) xmlMap.get("eb");
Map result = (Map) response.get("out");
Map resultCode = (Map) response.get("pub");
Assert.state(resultCode.get("RetCode").equals("0"), (String) resultCode.get("RetMsg"));
saveResearchICBC(id,userLogin,response);
return result;
}
8、结语
第一次做银企直联,大佬轻喷,有错必改!!!!
|