征信接口調用,解析(xml)


數據傳輸格式報文格式:xml
public CisReportRoot queryCisReport(PyQueryBean pyQueryBean) throws Exception {
CisReportRoot cisReportRoot = invokePy(pyQueryBean){
CisReportRoot cisReportRoot = queryCisReportFromPyServer(pyQueryBean);   } } 

pyQueryBean--CisReportRoot 
注意:接口數據傳輸通過xml,無論發送請求,還是獲取響應都需要經過經過xml格式轉化。 
1,CisReportRoot cisReportRoot = getCisReportRoot(doc); pyQueryBean--Map--doc--xmL
//實體轉化為Map 2,Map<String, String> map = CommonUtils.beanToMap(pyQueryBean);
//Map轉化為指定標簽的xml字符串 Map-doc-xml 3,String queryInfo = XmlUtil.createQueryCondition(map);
//從鵬元獲取Xml,轉化為doc xml-doc- 4,Document doc = pyClient.connectToPyClient(queryInfo);
//解析doc中數據,賦值到實體
5,CisReportRoot cisReportRoot = getCisReportRoot(doc); 具體實現如下:
2, public static Map<String, String> beanToMap(Object obj) { if (obj == null) { return null; } Map<String, String> map = new HashMap<>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); // 過濾class屬性 if (!"class".equals(key)) { // 得到property對應的getter方法 Method getter = property.getReadMethod(); Object value = getter.invoke(obj); map.put(key, String.valueOf(value)); } } } catch (Exception e) { System.out.println("transBean2Map@CommonUtils_Exception" + e); } return map; } 3, 構建請求xml public static String createQueryCondition(Map<String, String> map) throws Exception { Document document = DocumentHelper.createDocument(); document.setXMLEncoding(ENCODING); Element root = document.addElement("conditions"); Element conditionElement = root.addElement("condition"); conditionElement.addAttribute("queryType", map.get("queryType")); Element itemName = conditionElement.addElement("item"); itemName.addElement("name").addText("name"); itemName.addElement("value").addText(map.get("name") == null ? "" : map.get("name")); Element itemDocumentNo = conditionElement.addElement("item"); itemDocumentNo.addElement("name").addText("documentNo"); itemDocumentNo.addElement("value").addText(map.get("documentNo") == null ? "" : map.get("documentNo")); Element itemPhone = conditionElement.addElement("item"); itemPhone.addElement("name").addText("phone"); itemPhone.addElement("value").addText(map.get("phone") == null ? "" : map.get("phone")); Element itemQueryReasonID = conditionElement.addElement("item"); itemQueryReasonID.addElement("name").addText("queryReasonID"); itemQueryReasonID.addElement("value").addText(map.get("queryReasonID") == null ? "" : map.get("queryReasonID")); Element itemSubreportIDs = conditionElement.addElement("item"); itemSubreportIDs.addElement("name").addText("subreportIDs"); itemSubreportIDs.addElement("value").addText(map.get("subreportIDs") == null ? "" : map.get("subreportIDs")); Element itemRefID = conditionElement.addElement("item"); itemRefID.addElement("name").addText("refID"); itemRefID.addElement("value").addText(map.get("refID") == null ? "" : map.get("refID")); return document.asXML(); } 4,獲取鵬飛響應Xml /** * 連接到鵬飛服務端 * * @param queryInfo 查詢信息--Xml格式 * @return 返回查詢結果 */ public Document connectToPyClient(String queryInfo) throws Exception { try { Client client = new Client(new URL(configInfo.getPy_ssl_ip())); Object[] results = client.invoke(QUERY_REPORT, new Object[]{configInfo.getPy_username(), configInfo.getPy_password(), queryInfo, "xml"}); Document dom4j; if (results[FIRST_NODE] instanceof org.w3c.dom.Document) { //FIRST_NODE = 0 org.w3c.dom.Document doc = (org.w3c.dom.Document) results[FIRST_NODE]; org.w3c.dom.Element element = doc.getDocumentElement(); //獲取所有子節點 NodeList children = element.getChildNodes(); //獲取第一個子節點 //xml to dom dom4j = XmlUtil.getDoc(children.item(FIRST_NODE).getNodeValue()); //獲取根節點 Element root = dom4j.getRootElement(); Element statusElement = root.element(STATUS); String ba64; if (statusElement.getData().equals(SUCCESS)) { /*客戶端獲取該returnValue值后需要依次做以下工作: 1、 把returnValue值用Base64解碼,把字符串(string)轉成字節流(byte[]); 2、 把字節流解壓縮后,獲取到相應的多個輸出文件,其中html和pdf是壓縮文件; 3、 解析reports.xml獲取xml報告的詳細內容;*/ //1、 把returnValue值用Base64解碼,把字符串(string)轉成字節流(byte[]); ba64 = root.element(RETURN_VALUE).getData().toString(); byte[] re = Base64Utils.decode(ba64); //2、 把字節流解壓縮后,獲取到相應的多個輸出文件,其中html和pdf是壓縮文件; String xml = CompressStringUtil.decompress(re); logger.info(xml); //3、 解析reports.xml獲取xml報告的詳細內容; return XmlUtil.getDoc(xml); } else { StringBuilder sb = new StringBuilder(PyCreditServiceErrorEnum.PY_SYS_ERROR.getMsg()); String xml = XmlUtil.getString(dom4j); logger.error(xml); if (null != root.element("errorMessage")) { sb.append(", ").append(root.element("errorMessage").getData().toString()); logger.error("py server has problem, errorMessage: " + sb.toString()); } throw new CreditException(PyCreditServiceErrorEnum.PY_SYS_ERROR.getCode(), sb.toString()); } } return null; } catch (SocketTimeoutException e) { logger.error("level0_loadClient@PyClientService_Exception", e); throw new CreditException(PyCreditServiceErrorEnum.PY_SYS_TIMEOUT.getCode(), PyCreditServiceErrorEnum.PY_SYS_TIMEOUT.getMsg()); } catch (Exception e) { logger.error("level0_connectToPyClient@ConnectToPyClient_Exception", e); throw e; } } 5,解析xml報告中數據
CisReportRoot cisReportRoot = getCisReportRoot(doc);
總括:解析doc每一層節點,獲取屬性,當前子節點數據,以此類推分層解析。
思路:屬性,子節點List-map-通過反射給實體賦值
/**
     * @return com.pingan.credit.model.py.CisReportRoot
     * @Description: 解析報告里的數據
     * @author chiyuanzhen743
     * @date 2017/8/24 14:53
     */
    private CisReportRoot getCisReportRoot(Document doc) throws Exception {
        CisReportRoot cisReportRoot;
        Element root = doc.getRootElement();
     //(1)獲取根節點屬性 cisReportRoot
= getRootAttribute(root); Element cisReport = root.element("cisReport"); CisReportChild crc = new CisReportChild(); // 獲取報告節點的所有屬性 if (!ListUtil.isEmpty(cisReport.attributes())) { List<Attribute> eRootAttributeList = (List<Attribute>) cisReport.attributes(); crc = getChildReportAttribute(eRootAttributeList); } ReportElement re = new ReportElement(); //(2)獲取報告所有子節點數據 re = getCisReportChild(cisReport, re); crc.setReportElement(re); cisReportRoot.setCisReportChild(crc); return cisReportRoot; }
//(1)獲取根節點屬性
/**
     * 獲取根節點所有屬性
     *
     * @param root 根節點
     * @return 報告根節點對象
     */
    private CisReportRoot getRootAttribute(Element root) throws Exception {
        List<Attribute> attributeList = root.attributes();
        Map<String, String> result = attributeList.stream()
                .collect(Collectors.toMap(Attribute::getName, Attribute::getValue));
        CisReportRoot cisreportRoot = new CisReportRoot();
        CommonUtils.setValue(cisreportRoot, result);
        return cisreportRoot;
    }
//(2)獲取報告所有子節點數據
    /**
     * @param cisReport, re
     * @return com.pingan.credit.model.py.ReportElement
     * @Description: 獲取報告中 每個節點的數據
     * @date 2017/10/23 20:25
     */
    private ReportElement getCisReportChild(Element cisReport, ReportElement re)
            throws Exception {

        // 2.獲取身份認證 policeCheckInfo
        Element policeCheckInfoElement = cisReport.element("policeCheckInfo");
     //(3)獲取節點屬性 List
<Attribute> policeCheckInfoAttributeList = policeCheckInfoElement.attributes();
     //通過反射給實體賦值 PoliceCheckInfo pci
= getPoliceCheckInfoNode(policeCheckInfoElement, policeCheckInfoAttributeList); re.setPoliceCheckInfo(pci);
//(3)獲取節點屬性
xml樣例
<policeCheckInfo subReportType="10602" subReportTypeCost="96040" treatResult="1" errorMessage="">
<item>
    <name>測試一</name>
    <documentNo>14043019900217914X</documentNo>
    <result>1</result>
</item>
</policeCheckInfo>
 
 /**
     * @param policeCheckInfoElement, policeCheckInfoAttributeList
     * @return com.pingan.credit.model.py.PoliceCheckInfo
     * @Description: 身份認證節點
     * @author chiyuanzhen743
     * @date 2017/10/20 15:13
     */
    private PoliceCheckInfo getPoliceCheckInfoNode(Element policeCheckInfoElement,
                                                   List<Attribute> policeCheckInfoAttributeList) throws Exception {
        try {
            // 獲取子節點的全部屬性
            Map<String, String> attributeMap = policeCheckInfoAttributeList.stream()
                    .collect(Collectors.toMap(Attribute::getName, Attribute::getValue));
       //(4)獲取屬性給父類賦值,因為節點屬性是相同的,抽象為父類
            PoliceCheckInfo pci = (PoliceCheckInfo) CommonUtils.setValueOfSuperClass(PoliceCheckInfo.class, attributeMap);
            if (SUCCESS.equals(attributeMap.get("treatResult"))) {
                // 獲取身份認證內容節點
                List<Element> policeCheckInfoList = policeCheckInfoElement.element("item").elements();
          //(5)節點內容轉化為map Map
<String, String> resultMap = XmlUtil.getResultMap(policeCheckInfoList);
          //(6)反射賦值 pci
= (PoliceCheckInfo) CommonUtils.setValue(pci, resultMap); } else { throw new CreditException(PyCreditServiceErrorEnum.IDENTITY_NOT_MATCH.getCode(), PyCreditServiceErrorEnum.IDENTITY_NOT_MATCH.getMsg()); } return pci; } catch (Exception e) { logger.error("getPoliceCheckInfoNode@PyServiceImpl_Expection", e); throw e; } }
//(4)獲取屬性給父類賦值,因為節點屬性是相同的,抽象為父類。
/**
     * @param clazz, attributeMap
     * @return java.lang.Object
     * @Description: 通過反射給目標對象的父類設置屬性
     * @date 2017/8/30 9:42
     */
    public static Object setValueOfSuperClass(Class<?> clazz, Map<String, String> attributeMap) throws Exception {
        try {
            Object object = Class.forName(clazz.getName()).newInstance();
            Class<?> obj = object.getClass().getSuperclass();
            Field[] fields = obj.getDeclaredFields();
            setValue(object, attributeMap, fields);
            return object;
        } catch (Exception e) {
            logger.info(e.getMessage());
            throw e;
        }
    }

//(5)節點內容轉化為map

 /**
     * 將元素節點轉換成map
     */
    public static Map<String, String> getResultMap(List<Element> items) {
        Map<String, String> map = new HashMap<>(32);
        for (Element e : items) {
            if (StringUtils.isNotEmpty(e.getData().toString())) {
                map.put(e.getName(), e.getData().toString());
            }
        }
        return map;
    }

//(6)反射賦值

    /**
     * @param object, resultMap
     * @return java.lang.Object
     * @Description: 通過反射為實體類賦值
     * @date 2017/8/30 9:43
     */
    public static Object setValue(Object object, Map<String, String> resultMap) throws Exception {
        try {
            Class<?> obj = object.getClass();
            Field[] fields = obj.getDeclaredFields();
            setValue(object, resultMap, fields);

            return object;
        } catch (IllegalAccessException e) {
            logger.info("IllegalAccessException@CommonUtils:" + e.getMessage());
            throw e;
        } catch (Exception e) {
            logger.info("Exception@CommonUtils:" + e.getMessage());
            throw e;
        }
    }

 

 

 
         

 

 
         

 

 
         

 

 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM