在java中请求webservice接口并且处理xml解析实现代码

此为工具类,全类粘贴  (XMLParseUtil)

package com.ruoyi.common.core.utils.cytxml;

import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;



/**
 * 解析XML公用类:支持多重内部类解析 dom4j 支持
 *
 * @author huhaopeng
 */
public class XMLParseUtil {

    // -----------------------------------------------------------------------------------------------------------------------------------------//
    // Bean To Xml //
    // -----------------------------------------------------------------------------------------------------------------------------------------//
    /**
     * JAVA Bean 转换 XML 字符串 Describe:
     *
     * @author:huhaopeng
     * @param obj
     *            Object 传入 Body
     * @param header
     *            Object 传入 Header
     * @param paramName
     *            String OTA区分标识 ( qunar, ectrip )
     * @注: header 需要传入 application, processor, createUser return:void
     *     Date:2014-2-21
     */
    @SuppressWarnings( { "finally", "deprecation" })
    public static String beanToXML(final Object obj, final Object header,
                                   String paramName) throws Exception {
        // 获取头信息
        XmlHeaderParam param = DoXmlParamUtil.getXmlHeaderParam(paramName);

        // className:类全名
        String clsName = obj.getClass().getName();
        // 去掉类全名前面不需要的:例如 cn.xml.Context -> Context
        clsName = clsName.substring(clsName.lastIndexOf(".") + 1, clsName
                .length());
        // System.out.println(clsName);

        // 根据类名生成root
        Document doc = DocumentHelper.createDocument();
        // doc.addComment("Sample XML file generated by XMLSpy v2013 (http://www.altova.com)");
        // 添加根节点:
        Element root = null;
        if (clsName.indexOf("Request") != -1) {
            root = doc.addElement("qm:request");
            root.addNamespace("qm", param.getNamespaceRequest());
            root.addAttribute("xsi:schemaLocation", param.getAttributeXsi());
            root.addAttribute("xmlns:xsi", param.getAttributeXmlns());
        } else if (clsName.indexOf("Response") != -1) {
            root = doc.addElement("qm:response");
            root.addNamespace("qm", param.getNamespaceResponse());
            root.addAttribute("xsi:schemaLocation", param.getAttributeXsi());
            root.addAttribute("xmlns:xsi", param.getAttributeXmlns());
        }

        // 添加Header
        Element head = root.addElement("qm:header");

        complexTypeRecursive(header, head);

        Element body = root.addElement("qm:body");

        body.setAttributeValue("xsi:type", "qm:" + clsName);
        // bean属性
        complexTypeRecursive(obj, body);

        // 生成xml:String
        XMLWriter xw;
        StringWriter sw = new StringWriter();
        OutputFormat opf;
        String result = null;
        try {
            opf = OutputFormat.createCompactFormat();
            opf.setEncoding("UTF-8");
            xw = new XMLWriter(sw);
            xw.write(doc);
            result = sw.toString();
            xw.close();
            sw.close();

        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return result;
        }

    }

    /**
     * 递归: 获取 复杂类型 树结构方法。 Describe: objectToXML() use
     *
     * @author:huhaopeng
     * @param obj
     *            : Object(此节点对应对象)
     * @param parentElemen
     *            : Element(此节点) return:void Date:2014-2-21
     */
    @SuppressWarnings("unchecked")
    public static void complexTypeRecursive(Object obj, Element element) {
        Class cls = obj.getClass();
        String objName = cls.getSimpleName();
        // getDeclaredFields:获取bean中所有属性
        Field[] fields = cls.getDeclaredFields();
        String fieldName = "";
        if("String".equals(objName)){
            element.setText(obj.toString());
        }else{
            for (Field f : fields) {
                f.setAccessible(true);
                fieldName = f.getName();
                // System.out.println(f.getType());

                try {

                    PropertyDescriptor pd = new PropertyDescriptor(fieldName, cls);
                    Method getMethod = pd.getReadMethod();// 获得get方法
                    // 当前对象:o
                    Object o = getMethod.invoke(obj);// 执行get方法返回一个Object

                    // 判断是否为list属性
                    if ((".List").equals(f.getType().toString().substring(
                            f.getType().toString().lastIndexOf(".")))) {
                        List list = (ArrayList) o;
                        for (Object ob : list) {
                            Element emt = element.addElement("qm:" + fieldName);
                            // System.out.println("qm:" + fieldName);
                            complexTypeRecursive(ob, emt);
                        }
                    } else {
                        Element emt = element.addElement("qm:" + fieldName);
                        // 判断下个节点是否需要:为null说明不用加入xml中
                        if (null != o) {
                            // 判断节点o是否为基础类型:if(基础类型)else(非基础类型)
                            if ("java".equals(o.getClass().getName()
                                    .substring(0, 4))) {
                                emt.setText(o.toString());
                            } else {
                                // 递归调用
                                complexTypeRecursive(o, emt);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out
                            .println("Bean To Xml Exception : XMLParseUtil >> complexTypeRecursive() Throws!");
                }
            }
        }
    }

    // -----------------------------------------------------------------------------------------------------------------------------------------//
    // XML To Bean //
    // -----------------------------------------------------------------------------------------------------------------------------------------//

    /**
     * XML 转换 为 JACA BEAN Describe: bodyInfo 对应类中所有属性必须已经实例化,不能为NULL
     *
     * @author:huhaopeng
     * @param xml
     *            String
     * @param bodyInfo
     *            Object
     * @return return:Map Date:2014-2-22
     */
    @SuppressWarnings("unchecked")
    public static Map xmlToBean(String xml, Object header, Object bodyInfo)
            throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Document doc = null;

        try {
            // 读取并解析XML文档
            // SAXReader就是一个管道,用一个流的方式,把xml文件读出来
            // SAXReader reader = new SAXReader(); //User.hbm.xml表示你要解析的xml文档
            // Document document = reader.read(new File("User.hbm.xml"));
            // 下面的是通过解析xml字符串的
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML

            Element root = doc.getRootElement(); // 获取根节点
            // System.out.println("根节点:" + root.getName()); // 拿到根节点的名称
            String rootName = root.getName();
            Iterator rootIter = root.elementIterator();
            // 获取根节点下的子节点head
            Iterator headerIter = ((Element) rootIter.next()).elementIterator();
            Iterator bodyIter = ((Element) rootIter.next()).elementIterator();

            // 判断header节点是否有值,遍历header节点

            // Header: 递归塞值
            complexTypeRecursiveXmlToBean(header, headerIter);

            map.put("header", header);// map.put("header", rqstHeader);

            // Body: 递归塞值
            complexTypeRecursiveXmlToBean(bodyInfo, bodyIter);

            map.put("body", bodyInfo);

            // 遍历body节点(以传入类结构遍历,用"java"字符串 来判定是否为复杂类型)
            // getDeclaredFields:获取为引用类型数
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("XMLParseUtil.java Error: URL - xmlToBean() throw out");
        }
        return map;
    }

    /**
     * 请求的  Header xml 转  bean
     * Describe:
     * @author:huhaopeng
     * @param xml Header xml字符串
     * @param header header格式
     * @return
     * return:String
     * Date:2014-5-9
     */
    public static Object requestHeaderXmlTobean(String xml,Object header) {
        Document doc = null;

        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML

            Element root = doc.getRootElement(); // 获取根节点
            Iterator rootIter = root.elementIterator();
            // 获取根节点下的子节点head
            Iterator headerIter = ((Element) rootIter.next()).elementIterator();
            //Iterator bodyIter = ((Element) rootIter.next()).elementIterator();

            // Header: 递归塞值
            complexTypeRecursiveXmlToBean(header, headerIter);

            return header;

            // getDeclaredFields:获取为引用类型数
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("XMLParseUtil.java Error: URL - xmlToBean() throw out");
        }


        return null;
    }

    /**
     * 递归:将xml中对应结构的值塞入对象中 Describe:
     *
     * @author:huhaopeng
     * @param obj
     *            Object 对象结构模型
     * @param iterss
     *            获取的XML文件:body中的所有子节点 return:void Date:2014-2-22
     */
    @SuppressWarnings("unchecked")
    public static void complexTypeRecursiveXmlToBean(Object obj, Iterator iterss) {
        Class cls = obj.getClass();
        Field[] fields = cls.getDeclaredFields();
        String upName;

        // 获取(Iterator iterss)所有对象的值。
        List<Element> eList = new ArrayList<Element>();
        while (iterss.hasNext()) {
            Element e = (Element) iterss.next();
            eList.add(e);
        }

        for (Field field : fields) {
            field.setAccessible(true);
            // 当前 Node
            Element emt = null;
            // 判断obj此属性 在xml中是否存在(如果不是必须的,有可能不会传值.)
            boolean isContinue = true;
            for (Element e : eList) {
                if (e.getName().equals(field.getName())) {
                    isContinue = false;
                    emt = e;
                } else {

                }
            }
            if (isContinue == true) {
                continue;
            }// class

//            if ("class com.ectrip.tour.service.model.chema.qunar.request.CreateOrderForBeforePaySyncRequestBody$OrderInfo$VisitPerson"
//                    .equals(field.getType().toString())) {
//                System.out.println("出错位置进来了");
//            }
            String text = emt.getText();
            try {
                // PropertyDescriptor:用来连接 <类当前属性> <get>和<set>方法
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(),
                        cls);
                Method getMethod = pd.getReadMethod();// 获得get方法
                // 当前对象:o
                Object o = getMethod.invoke(obj);// 执行get方法返回一个Object
                // 判断是否为list属性
//                System.out.println("field.getType().toString()" + field.getType().toString());
                if ((".List").equals(field.getType().toString().substring(
                        field.getType().toString().lastIndexOf(".")))) {
                    List list = (ArrayList) o;

                    // 判断是否有对象:有就添加到list对象中
                    for (Element element : eList) {// while (iterss.hasNext())
                        // {//iterss 这时候 里面存的已经是
                        // List中的所有对象了

                        String classForName = field.getGenericType().toString()
                                .substring(
                                        field.getGenericType().toString()
                                                .indexOf("<") + 1,
                                        field.getGenericType().toString()
                                                .lastIndexOf(">"));
                        Object ob = Class.forName(classForName).newInstance();
                        // 将对象塞入list
                        list.add(ob);
                        // 获取节点下所有属性
                        Iterator ite = element.elementIterator();
                        // 给塞入list的对象赋值
                        complexTypeRecursiveXmlToBean(ob, ite);
                    }
                } else {
                    upName = field.getName().substring(0, 1).toUpperCase()
                            + field.getName().substring(1);
                    // System.out.println("java".equals(o.getClass().getName().substring(0,
                    // 4)));
                    if ("java".equals(o.getClass().getName().substring(0, 4))) {
                        // 基础类型:给对象塞值
                        obj.getClass().getMethod("set" + upName, String.class)
                                .invoke(obj, text);
                        // System.out.println("set" + upName +
                        // ": "+text+" --------OK!");
                    } else {
                        // 复杂类型:递归
                        Iterator eIter = emt.elementIterator();
                        complexTypeRecursiveXmlToBean(o, eIter);
                    }
                }
            } catch (Exception e) {
                System.out
                        .println("XMLParseUtil.java Error: URL - xmlToBean()-> complexTypeRecursiveXmlToBean() throw out");
                e.printStackTrace();
            }
        }
    }

    /* ---------------------------------------------- 携程结构  ---------------------------------------------- */

    @SuppressWarnings("finally")
    public static String beanToXML_XC(final Object obj) throws Exception {

        // className:类名
        String clsName = obj.getClass().getSimpleName();

        // 根据类名生成root
        Document doc = DocumentHelper.createDocument();
        // doc.addComment("Sample XML file generated by XMLSpy v2013 (http://www.altova.com)");
        // 添加根节点:
        Element root = doc.addElement(clsName);
        complexTypeRecursiveXC(obj, root);

        // 生成xml:String
        XMLWriter xw;
        StringWriter sw = new StringWriter();
        OutputFormat opf;
        String result = null;

        try {
            opf = OutputFormat.createCompactFormat();
            opf.setEncoding("UTF-8");
            xw = new XMLWriter(sw);
            xw.write(doc);
            result = sw.toString();
            xw.close();
            sw.close();

        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return result;
        }
    }

    /**
     * 递归: 获取 复杂类型 树结构方法。 Describe: objectToXML() use
     *
     * @author:huhaopeng
     * @param obj
     *            : Object(此节点对应对象)
     * @param parentElemen
     *            : Element(此节点) return:void Date:2014-2-21
     */
    @SuppressWarnings("unchecked")
    private static void complexTypeRecursiveXC(Object obj, Element element) {

        Class cls = obj.getClass();
        String objName = cls.getSimpleName();
        // getDeclaredFields:获取bean中所有属性
        Field[] fields = cls.getDeclaredFields();
        String fieldName = "";

        if("String".equals(objName)){
            Element emt = element.addElement("string");
            emt.setText(obj.toString());
        }else{
            for (Field f : fields) {
                f.setAccessible(true);
                fieldName = f.getName();
                // System.out.println(f.getType());

                try {

                    PropertyDescriptor pd = new PropertyDescriptor(fieldName, cls);
                    Method getMethod = pd.getReadMethod();// 获得get方法
                    // 当前对象:o
                    Object o = getMethod.invoke(obj);// 执行get方法返回一个Object

                    // 判断是否为list属性
                    if ((".List").equals(f.getType().toString().substring(
                            f.getType().toString().lastIndexOf(".")))) {
                        List list = (ArrayList) o;

                        for (Object ob : list) {
                            char[] ch =  fieldName.toCharArray();

                            int i = 0;
                            StringBuffer strName = null;

                            if("ota".equals(fieldName.substring(0,3))){
                                i = 3;
                                strName = new StringBuffer(String.valueOf(ch[0]).toUpperCase()
                                        + String.valueOf(ch[1]).toUpperCase()
                                        + String.valueOf(ch[2]).toUpperCase());
                            }else{
                                i = 1;
                                strName = new StringBuffer(String.valueOf(ch[0]).toUpperCase() );
                            }

                            for (; i < ch.length; i++) {
                                strName.append(ch[i]);
                            }

                            Element emt = element.addElement(strName.toString());
                            // System.out.println("qm:" + fieldName);
                            complexTypeRecursiveXC(ob, emt);
                        }
                    } else {

                        // 判断下个节点是否需要:为null说明不用加入xml中
                        if (null != o) {

                            char[] ch =  fieldName.toCharArray();

                            int i = 0;
                            StringBuffer strName = null;

                            if("ota".equals(fieldName.substring(0,3))){
                                i = 3;
                                strName = new StringBuffer(String.valueOf(ch[0]).toUpperCase()
                                        + String.valueOf(ch[1]).toUpperCase()
                                        + String.valueOf(ch[2]).toUpperCase());
                            }else{
                                i = 1;
                                strName = new StringBuffer(String.valueOf(ch[0]).toUpperCase() );
                            }

                            for (; i < ch.length; i++) {
                                strName.append(ch[i]);
                            }

                            Element emt = element.addElement(strName.toString());


                            // 判断节点o是否为基础类型:if(基础类型)else(非基础类型)
                            if ("java".equals(o.getClass().getName()
                                    .substring(0, 4))) {
                                emt.setText(o.toString());
                            } else {
                                // 递归调用
                                complexTypeRecursiveXC(o, emt);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out
                            .println("Bean To Xml Exception : XMLParseUtil >> complexTypeRecursive() Throws!");
                }
            }
        }
    }


    /**
     * XML 转换 为 JACA BEAN Describe: bodyInfo 对应类中所有属性必须已经实例化,不能为NULL
     *
     * @author:huhaopeng
     * @param xml
     *            String
     * @param bodyInfo
     *            Object
     * @return return:Map Date:2014-2-22
     */
    @SuppressWarnings("unchecked")
    public static Object xmlToBean_XC(String xml, Object bodyInfo)
            throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Document doc = null;

        try {
            // 读取并解析XML文档
            // SAXReader就是一个管道,用一个流的方式,把xml文件读出来
            // SAXReader reader = new SAXReader(); //User.hbm.xml表示你要解析的xml文档
            // Document document = reader.read(new File("User.hbm.xml"));
            // 下面的是通过解析xml字符串的
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML

            Element root = doc.getRootElement(); // 获取根节点
            // System.out.println("根节点:" + root.getName()); // 拿到根节点的名称
            String rootName = root.getName();
            Iterator rootIter = root.elementIterator();

            // Header: 递归塞值
            complexTypeRecursiveXmlToBeanXC(bodyInfo, rootIter);


        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("XMLParseUtil.java Error: URL - xmlToBean() throw out");
        }
        return bodyInfo;
    }

    /**
     * 递归:将xml中对应结构的值塞入对象中 Describe:
     *
     * @author:huhaopeng
     * @param obj
     *            Object 对象结构模型
     * @param iterss
     *            获取的XML文件:body中的所有子节点 return:void Date:2014-2-22
     */
    @SuppressWarnings("unchecked")
    private static void complexTypeRecursiveXmlToBeanXC(Object obj, Iterator iterss) {
        Class cls = obj.getClass();
        Field[] fields = cls.getDeclaredFields();
        String upName;

        // 获取(Iterator iterss)所有对象的值。
        List<Element> eList = new ArrayList<Element>();
        while (iterss.hasNext()) {
            Element e = (Element) iterss.next();

            char[] ch =  e.getName().toCharArray();
            int i = 0;
            StringBuffer strName = null;
            if("ota".equals(e.getName().substring(0,3)) ){
                i = 3;
                strName = new StringBuffer(String.valueOf(ch[0]).toLowerCase()
                        + String.valueOf(ch[1]).toLowerCase()
                        + String.valueOf(ch[2]).toLowerCase());
            }else{
                i = 1;
                strName = new StringBuffer(String.valueOf(ch[0]).toLowerCase() );
            }

            for (; i < ch.length; i++) {

                strName.append(ch[i]);
            }
            e.setName(strName.toString());

            eList.add(e);
        }

        for (Field field : fields) {
            field.setAccessible(true);
            // 当前 Node
            Element emt = null;
            // 判断obj此属性 在xml中是否存在(如果不是必须的,有可能不会传值.)
            boolean isContinue = true;
            for (Element e : eList) {
                if (e.getName().equals(field.getName())) {
                    isContinue = false;
                    emt = e;
                } else {

                }
            }
            if (isContinue == true) {
                continue;
            }// class

            String text = emt.getText();
            try {
                // PropertyDescriptor:用来连接 <类当前属性> <get>和<set>方法
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(),
                        cls);
                Method getMethod = pd.getReadMethod();// 获得get方法
                // 当前对象:o
                Object o = getMethod.invoke(obj);// 执行get方法返回一个Object
                // 判断是否为list属性
//                System.out.println("field.getType().toString()" + field.getType().toString());
                if ((".List").equals(field.getType().toString().substring(
                        field.getType().toString().lastIndexOf(".")))) {
                    List list = (ArrayList) o;

                    // 判断是否有对象:有就添加到list对象中
                    for (Element element : eList) {// while (iterss.hasNext())
                        // {//iterss 这时候 里面存的已经是
                        // List中的所有对象了

                        String classForName = field.getGenericType().toString()
                                .substring(
                                        field.getGenericType().toString()
                                                .indexOf("<") + 1,
                                        field.getGenericType().toString()
                                                .lastIndexOf(">"));
                        Object ob = Class.forName(classForName).newInstance();
                        // 将对象塞入list
                        list.add(ob);
                        // 获取节点下所有属性
                        Iterator ite = element.elementIterator();
                        // 给塞入list的对象赋值
                        complexTypeRecursiveXmlToBeanXC(ob, ite);
                    }
                } else {
                    upName = field.getName().substring(0, 1).toUpperCase()
                            + field.getName().substring(1);
                    // System.out.println("java".equals(o.getClass().getName().substring(0,
                    // 4)));
                    if ("java".equals(o.getClass().getName().substring(0, 4))) {
                        // 基础类型:给对象塞值
                        obj.getClass().getMethod("set" + upName, String.class)
                                .invoke(obj, text);
                        // System.out.println("set" + upName +
                        // ": "+text+" --------OK!");
                    } else {
                        // 复杂类型:递归
                        Iterator eIter = emt.elementIterator();
                        complexTypeRecursiveXmlToBeanXC(o, eIter);
                    }
                }
            } catch (Exception e) {
                System.out
                        .println("XMLParseUtil.java Error: URL - xmlToBean()-> complexTypeRecursiveXmlToBean() throw out");
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
//        long a=System.currentTimeMillis();
//        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><request xmlns=\"http://piao.qunar.com/2013/QMenpiaoRequestSchema\"><header><application>Agent</application><processor>SupplierDataExchangeProcessor</processor><version>v2.0.0</version><bodyType>GetProductByQunarRequestBody</bodyType><createUser>test</createUser><createTime>2014-05-09 15:19:46</createTime><supplierIdentity>DINGYOU</supplierIdentity></header><body xsi:type=\"GetProductByQunarRequestBody\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><method>ALL</method><currentPage>1</currentPage><pageSize>100</pageSize><resourceId></resourceId></body></request>";
//        RequestHeader header = (RequestHeader)requestHeaderXmlTobean(xml, new RequestHeader());
//        System.out.println(header.getCreateUser());
//
//        System.out.println("\r<br>执行耗时 : "+(System.currentTimeMillis()-a)/1000f+" 秒 ");


        //测试字符串首字符大小写切换
//        char[] tst =  "aaAbbcc11".toCharArray();
//        StringBuffer str = new StringBuffer(String.valueOf(tst[0]).toUpperCase() );
//
//        for (int i = 1; i < tst.length; i++) {
//
//            str.append(tst[i]);
//        }
//        System.out.println(str);


//        //TODO  测试  bean to xml 会不会异常情况
//        CtripTourGetPORQ testBody = new CtripTourGetPORQ();
//        testBody.getRequestHeader().setVersion("1.0");
//        testBody.getRequestHeader().setTimeStamp("2013/10/02 22:53:37");
//        testBody.getRequestHeader().setMessageID(null);
//        testBody.getRequestHeader().setLanguage("Chinese");
//        testBody.getRequestHeader().setOtaName("Ctrip");
//        testBody.getRequestHeader().setVendorToken("Ctrip1234");
//        testBody.getRequestHeader().setVendorID("8817");
//
//        testBody.setOtapoRefNum("1234567890");
//
//        try {
//            String str = beanToXML_XC(testBody);
//            System.out.println(str);
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }

        //TODO  测试   xml to bean 会不会异常情况
//        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
//                        "<CtripTourGetPORQ>" +
//                            "<RequestHeader>" +
//                                "<Version>0.1</Version>" +
//                                "<TimeStamp>2014-01-03T22:53:37</TimeStamp>" +
//                                "<Language>Chinese</Language>" +
//                                "<MessageID />" +
//                                "<OtaName>Ctrip</OtaName>" +
//                                "<VendorToken>ctrip1234</VendorToken>" +
//                                "<VendorID>5872</VendorID>" +
//                            "</RequestHeader>" +
//                            "<OtapoRefNum>22125639</OtapoRefNum>" +
//                        "</CtripTourGetPORQ>";
//        try {
//            CtripTourGetPORQ body = (CtripTourGetPORQ)xmlToBean_XC(xml, new CtripTourGetPORQ());
//            System.out.println("版本 : " + body.getRequestHeader().getVersion());
//            System.out.println("供应商编码 : " + body.getRequestHeader().getVendorID());
//            System.out.println("携程采购单票据号 : " + body.getOtapoRefNum());
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
    }

}
View Code

maven依赖如下:

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.12</version>
        </dependency>

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.13</version>
        </dependency>

<dependency>
            <groupId>wsdl4j</groupId>
            <artifactId>wsdl4j</artifactId>
        </dependency>

<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
        </dependency>

<dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
View Code

webservice接口在java中解析并且判断是否请求成功 ,如:http://114.55.29.159:8345/services/ectripOTOService?wsdl 

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.constant.ConsumeConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.TimeFormat;
import com.ruoyi.common.core.utils.baidu.HttpWS;
import com.ruoyi.common.core.utils.cytxml.DoXmlParamUtil;
import com.ruoyi.common.core.utils.cytxml.EncryptUtil;
import com.ruoyi.common.core.utils.cytxml.ResponseHeader;
import com.ruoyi.common.core.utils.cytxml.XMLParseUtil;
import com.ruoyi.common.core.utils.sign.Base64;
import com.ruoyi.job.domain.Dto.ConsumeInfo;
import com.ruoyi.pw.api.client.RemoteOrderMasterService;
import com.ruoyi.pw.api.domain.ConsumeNotice;
import com.ruoyi.pw.api.domain.consume.NoticeOrderConsumedRequestBody;
import com.ruoyi.pw.api.domain.consume.NoticeOrderConsumedResponseBody;
import com.ruoyi.system.api.RemoteDeptService;
import com.ruoyi.system.api.RemoteDictService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.api.domain.SysUser;
import org.json.JSONStringer;
import org.json.XML;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
View Code
private String sendData(String jsonData, String url) {
        try {
            Map mapJson = JSONObject.parseObject(jsonData, Map.class);
            String key = (String) mapJson.get("key");
            String requestJSON = (String) mapJson.get("requestJSON");
            // 推送数据
            //String response = HttpUtil.postGeneralUrl(url, "application/json", requestJSON, "utf-8");
            String soapXml = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:impl=\"http://impl.ectripoto.service.openapi.b2b.ectrip.com\">\n" +
                    "   <soapenv:Header/>\n" +
                    "   <soapenv:Body>\n" +
                    "      <impl:doOTORequest soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" +
                    "         <method xsi:type=\"soapenc:string\" xs:type=\"type:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xs=\"http://www.w3.org/2000/XMLSchema-instance\">noticeOrderConsumed</method>\n" +
                    "         <requestParam xsi:type=\"soapenc:string\" xs:type=\"type:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xs=\"http://www.w3.org/2000/XMLSchema-instance\">" + requestJSON + "</requestParam>\n" +
                    "      </impl:doOTORequest>\n" +
                    "   </soapenv:Body>\n" +
                    "</soapenv:Envelope>";
            String response = HttpWS.postSoap1_1(url, soapXml, "", null, null);
            System.out.println(response + "推送成功后的返回数据");
            org.json.JSONObject jsonObject = XML.toJSONObject(response);
            Map maps = (Map) JSON.parse(jsonObject.toString());
            String code = null;
            if (!maps.isEmpty()) {
                JSONObject envelope = JSON.parseObject(maps.get("soapenv:Envelope").toString());
                JSONObject soapenv = JSON.parseObject(envelope.get("soapenv:Body").toString());
                JSONObject doOTORequestResponse = JSON.parseObject(soapenv.get("ns1:doOTORequestResponse").toString());
                JSONObject doOTORequestReturn = JSON.parseObject(doOTORequestResponse.get("doOTORequestReturn").toString());
                JSONObject content = JSON.parseObject(doOTORequestReturn.get("content").toString());
                code = content.get("data").toString();
            }
            byte[] xmlByte = Base64.decode(code);
            String responseXML = null;
            try {
                responseXML = new String(xmlByte, "UTF-8");
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            Map map = XMLParseUtil.xmlToBean(responseXML, new ResponseHeader(), new NoticeOrderConsumedResponseBody());
            System.out.println(map);
            ResponseHeader header = (ResponseHeader) map.get("header");
            String headerCode = header.getCode();
            //NoticeOrderConsumedResponseBody responsebody = null;
            //responsebody = (NoticeOrderConsumedResponseBody) map.get("body");

            // 1.判定header返回值,是否为1000
            if ("1000".equals(headerCode)) {
                // 消费通知OTA成功!
                System.out.println("用户消费通知OTA成功!");
                return "";
            } else {
                // 消费通知OTA连接成功,返回异常信息:
                System.out.println("用户消费通知OTA:连接成功,出现异常:");
                System.out.println("异常状态码:" + headerCode.trim());
                System.out.println("异常详细信息:" + header.getDescribe().trim());
                return header.getDescribe().trim();
            }
        } catch (Exception e) {
            // 4. httpPost请求出现异常
            e.printStackTrace();
            System.out.println("用户消费通知OTA:httpPost请求出现异常:");
            //                e.printStackTrace();
            return "消费通知异常";
        }
    }
View Code

其中TttpWS.postSoap1_1接口是获取webservice请求之后的结果。TttpWS.postSoap1_1代码如下:

public static String postSoap1_1(String postUrl, String soapXml, String soapAction, String user,String pass) {
        String retStr = "";
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(reWriteUrl(postUrl));

        // 需要用户名密码验证
        if(StringUtils.isNotEmpty(user)){
            httpPost.addHeader(new BasicHeader("Authorization","Basic "
                    + Base64.encode((user+":"+pass).getBytes())));
        }

        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(socketTimeout)
                .setConnectTimeout(connectTimeout).build();
        httpPost.setConfig(requestConfig);

        if(soapAction != null){
            soapAction = "";
        }
        try {
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
            httpPost.setHeader("SOAPAction", soapAction);
            StringEntity data = new StringEntity(soapXml, Charset.forName("UTF-8"));
            httpPost.setEntity(data);
            CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                // 打印响应内容
                retStr = EntityUtils.toString(httpEntity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            try {
                if(closeableHttpClient != null){
                    closeableHttpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return retStr;
    }
View Code
NoticeOrderConsumedResponseBody工具类如下:
package com.ruoyi.pw.api.domain.consume;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "NoticeOrderConsumedResponseBody", propOrder = {
        "message"
})
public class NoticeOrderConsumedResponseBody extends ResponseBody{

    @XmlElement(required = true)
    protected String message;

    public NoticeOrderConsumedResponseBody() {
        super();
        this.message = "";
    }

    /**
     * Gets the value of the message property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getMessage() {
        return message;
    }

    /**
     * Sets the value of the message property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setMessage(String value) {
        this.message = value;
    }
}
View Code
ResponseHeader工具类如下:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2014.04.22 at 02:06:23 ���� CST 
//


package com.ruoyi.common.core.utils.cytxml;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;


import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;


/**
 * 门票数据头类型,该类型不得以任何形式继承。
 *
 * <p>Java class for ResponseHeader complex type.
 *
 * <p>The following schema fragment specifies the expected content contained within this class.
 *
 * <pre>
 * &lt;complexType name="ResponseHeader">
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;sequence>
 *         &lt;element name="application" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         &lt;element name="processor" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         &lt;element name="version" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         &lt;element name="bodyType" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         &lt;element name="createUser" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         &lt;element name="createTime" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         &lt;element name="code" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         &lt;element name="describe" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       &lt;/sequence>
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ResponseHeader", propOrder = {
        "application",
        "processor",
        "version",
        "bodyType",
        "createUser",
        "createTime",
        "code",
        "describe"
})
public class ResponseHeader {

    @XmlElement(required = true, defaultValue = "tour.ectrip.com")
    protected String application;
    @XmlElement(required = true, defaultValue = "DataExchangeProcessor")
    protected String processor;
    @XmlElement(required = true)
    protected String version;
    @XmlElement(required = true)
    protected String bodyType;
    @XmlElement(required = true)
    protected String createUser;
    @XmlElement(required = true)
    protected String createTime;
    @XmlElement(required = true)
    protected String code;
    @XmlElement(required = true)
    protected String describe;

    public ResponseHeader() {
        super();
        this.application = "";
        this.processor = "";
        this.version = "";
        this.bodyType = "";
        this.createUser = "";
        this.createTime = "";
        this.code = "";
        this.describe = "";
    }

    public ResponseHeader(String application, String processor, String version,
                          String bodyType, String createUser, String createTime, String code,
                          String describe) {
        super();
        this.application = application;
        this.processor = processor;
        this.version = version;
        this.bodyType = bodyType;
        this.createUser = createUser;
        this.createTime = createTime;
        this.code = code;
        this.describe = describe;
    }

    /**
     * Gets the value of the application property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getApplication() {
        return application;
    }

    /**
     * Sets the value of the application property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setApplication(String value) {
        this.application = value;
    }

    /**
     * Gets the value of the processor property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getProcessor() {
        return processor;
    }

    /**
     * Sets the value of the processor property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setProcessor(String value) {
        this.processor = value;
    }

    /**
     * Gets the value of the version property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getVersion() {
        return version;
    }

    /**
     * Sets the value of the version property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setVersion(String value) {
        this.version = value;
    }

    /**
     * Gets the value of the bodyType property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getBodyType() {
        return bodyType;
    }

    /**
     * Sets the value of the bodyType property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setBodyType(String value) {
        this.bodyType = value;
    }

    /**
     * Gets the value of the createUser property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getCreateUser() {
        return createUser;
    }

    /**
     * Sets the value of the createUser property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setCreateUser(String value) {
        this.createUser = value;
    }

    /**
     * Gets the value of the createTime property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getCreateTime() {
        return createTime;
    }

    /**
     * Sets the value of the createTime property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setCreateTime(String value) {
        this.createTime = value;
    }

    /**
     * Gets the value of the code property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getCode() {
        return code;
    }

    /**
     * Sets the value of the code property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setCode(String value) {
        this.code = value;
    }

    /**
     * Gets the value of the describe property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDescribe() {
        return describe;
    }

    /**
     * Sets the value of the describe property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDescribe(String value) {
        this.describe = value;
    }

}
View Code

 

 
 
posted @ 2021-10-14 10:57  初见如月  阅读(978)  评论(0编辑  收藏  举报