WebService soap报文请求并且将响应报文解析

测试类为:

import com.alibaba.druid.util.StringUtils;
import org.dom4j.io.SAXReader;
import org.jdom2.Document;

import java.util.Map;

/**
 * @author raychiu
 * @date 2019/5/7  -15:50
 */
public class SoapTest {
    public static void main(String[] args) {
        StringBuilder soap=new StringBuilder(); //构造请求报文
        soap.append(" <soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:proc='http://xmlns.oracle.com/apps/cux/rest/PageInquiryFaAssetSrv/process/' xmlns:msg='http://soa.cmcc.com/MsgHeader'>");
        soap.append(" <soapenv:Header/>");
        //soap.append(" <HZWFService  xmlns=\"http://www.huizhengtech.com/webservice/workflow\"");
        //soap.append(" xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"");
        //soap.append(" SOAP-ENV:actor=\"http://www.w3.org/2003/05/soap-envelope/role/next\">admin&admin</HZWFService>");
        //soap.append(" </soapenv:Header>");
        soap.append(" <soapenv:Body>");
        soap.append(" <proc:PROCESS_Input>");
        soap.append(" <proc:InputParameters>");
        soap.append(" <proc:MSGHEADER>");
        soap.append(" <msg:SOURCESYSTEMID>YJY-RMS</msg:SOURCESYSTEMID>");
        soap.append(" <msg:SOURCESYSTEMNAME>资产</msg:SOURCESYSTEMNAME>");
        soap.append(" <msg:TOKEN>882e030d6b8b02b6b90482dda34d9fe820190506</msg:TOKEN>");
        soap.append(" <msg:USER_ID xsi:nil='true' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'/>");
        soap.append(" <msg:USER_NAME xsi:nil='true' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'/>");
        soap.append(" <msg:USER_PASSWD xsi:nil='true' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'/>");
        soap.append(" <msg:SUBMIT_DATE xsi:nil='true' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'/>");
        soap.append(" <msg:PAGE_SIZE xsi:nil='true' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'/>");
        soap.append(" <msg:CURRENT_PAGE xsi:nil='true' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'/>");
        soap.append(" <msg:TOTAL_RECORD xsi:nil='true' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'/>");
        soap.append(" <msg:PROVINCE_CODE>YJY</msg:PROVINCE_CODE>");
        soap.append(" <msg:ROUTE_CODE xsi:nil='true' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'/>");
        soap.append(" <msg:TRACE_ID xsi:nil='true' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'/>");
        soap.append(" <msg:RESERVED_1 xsi:nil='true' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'/>");
        soap.append(" <msg:RESERVED_2 xsi:nil='true' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'/>");
        soap.append(" </proc:MSGHEADER>");
        soap.append(" <proc:BOOK_TYPE_CODE>YJYMC_FA_701010</proc:BOOK_TYPE_CODE>");
        soap.append(" <proc:PERIOD_NAME>2019-03</proc:PERIOD_NAME>");
        soap.append(" <proc:ASSET_NUMBER xsi:nil='true' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'/>");
        soap.append(" <proc:QUERY_EXT xsi:nil='true' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'/>");
        soap.append(" <proc:LAST_UPDATE_START xsi:nil='true' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'/>");
        soap.append(" <proc:LAST_UPDATE_END xsi:nil='true' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'/>");
        soap.append(" </proc:InputParameters>");
        soap.append(" </proc:PROCESS_Input>");
        soap.append(" </soapenv:Body>");
        soap.append(" </soapenv:Envelope>");
        String requestSoap=soap.toString();

        String serviceAddress="http://IP:端口/地址?wsdl";   //服务地址(将url替换成自己项目的地址)
        String charSet="utf-8";
        String contentType="text/xml; charset=utf-8";

        //第一步:调用方法getResponseSoap。返回响应报文和状态码

       Map<String,Object> responseSoapMap=SoapUtil.responseSoap(requestSoap, serviceAddress, charSet, contentType);
        Integer statusCode=(Integer)responseSoapMap.get("statusCode");
        if(statusCode==200){
            String responseSoap=(String)responseSoapMap.get("responseSoap");
            System.out.println("返回的报文为----"+responseSoap);
            String targetNodeName="ESB_RETURN_CODE";
            //第二步:调用strXmlToDocument方法。将字符串类型的XML的响应报文 转化成Docunent结构文档

            Document doc=Jdom2XMLUtil.strXmlToDocument(responseSoap);
            //第三步:调用getValueByElementName方法。递归获得目标节点的值
            String result= Jdom2XMLUtil.getValueByElementName(doc,targetNodeName);
            if(!StringUtils.isEmpty(result)){
                System.out.println(result);
            }else{
                System.out.println("没有此节点或者没有值!");
            }
        }else{
                System.out.println("请求失败!");
        }
    }
}

soap工具类:

 

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author raychiu
 * @date 2019/5/7  -15:52
 */
public class SoapUtil {

/**
 * <p>Description: 根据请求报文,请求服务地址获取 响应报文
 * @param requestSoap  请求报文
 * @param serviceAddress 响应报文
 * @param charSet 字符集
 * @param contentType  类型
 * @return  map封装的 服务器响应参数和返回报文.PS:statusCode :200正常响应。responseSoap:响应报文
 * <p>thinking: </p>
 *
 * @author  huoge
 */
public  static Map<String,Object> responseSoap(String requestSoap,String serviceAddress,String charSet, String contentType){
        String responseSoap="";
        Map<String,Object> resultmap=new HashMap<String,Object>();
        PostMethod postMethod = new PostMethod(serviceAddress);
        byte[] b = new byte[0];
        try {
            b = requestSoap.getBytes(charSet);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        InputStream is = new ByteArrayInputStream(b, 0, b.length);
        RequestEntity re = new InputStreamRequestEntity(is, b.length, contentType);
        postMethod.setRequestEntity(re);
        HttpClient httpClient = new HttpClient();
        int statusCode = 0;
        try {
            statusCode = httpClient.executeMethod(postMethod);
            resultmap.put("statusCode", statusCode);
        } catch (IOException e) {
            throw new RuntimeException("执行http请求失败", e);
        }
        if (statusCode == 200) {
        try {
            responseSoap = postMethod.getResponseBodyAsString();
            resultmap.put("responseSoap", responseSoap);
        } catch (IOException e) {
            throw new RuntimeException("获取请求返回报文失败", e);
        }
        } else {
            throw new RuntimeException("请求失败:" + statusCode);
        }
            return resultmap;
        }
}

XML解析工具类:

 

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.xml.sax.InputSource;

import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author raychiu
 * @date 2019/5/7  -16:22
 */
public class Jdom2XMLUtil {
    /**
          * <p>Description:将字符串类型的XML 转化成Docunent文档结构</p>
          * @param parseStrXml 待转换的xml 字符串
          * @return Document
          *
          * @author  huoge
          */
    public static Document strXmlToDocument(String parseStrXml){
        StringReader read = new StringReader(parseStrXml);
        //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
        InputSource source = new InputSource(read);
        //创建一个新的SAXBuilder
        SAXBuilder sb = new SAXBuilder();   // 新建立构造器
        Document doc = null;
        try {
            doc = sb.build(source);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return doc;

    }
    /**
     * <p>Description: 根据目标节点名获取值</p>
     * @param doc 文档结构
     * @param finalNodeName  最终节点名
     * @return
     *
     * @author  huoge
     */
    public static String getValueByElementName(Document doc,String finalNodeName){
        Element root = doc.getRootElement();
        HashMap<String,Object> map=new HashMap<String,Object>();
        //调用getChildAllText方法。获取目标子节点的值
        Map<String,Object> resultmap=getChildAllText(doc, root,map);
        String result=(String)resultmap.get(finalNodeName);
        return result;
    }


    /**
     * <p>Description: 递归获得子节点的值</p>
     * @param doc 文档结构
     * @param e  节点元素
     * @param resultmap  递归将值压入map中
     * @return
     *
     * @author  huoge
     */
    public static Map<String ,Object> getChildAllText(Document doc, Element e,HashMap<String,Object> resultmap)
    {
        if (e != null)
        {
            if (e.getChildren() != null)   //如果存在子节点
            {
                List<Element> list = e.getChildren();
                for (Element el : list)    //循环输出
                {
                    if(el.getChildren().size() > 0)   //如果子节点还存在子节点,则递归获取
                    {
                        getChildAllText(doc, el,resultmap);
                    }
                    else
                    {
                        resultmap.put(el.getName(), el.getTextTrim());  //将叶子节点值压入map
                    }
                }
            }
        }
        return resultmap;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章