zoukankan      html  css  js  c++  java
  • Java 发送SOAP请求调用WebService,解析SOAP报文

    https://blog.csdn.net/Peng_Hong_fu/article/details/80113196

    记录测试代码

    SoapUI调用路径

    http://localhost:8082/*/webservices/**Service?wsdl

    import org.apache.commons.lang.StringUtils;
    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Element;
    import org.dom4j.xpath.DefaultXPath;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.Base64;
    import java.util.Collections;
    import java.util.List;
    
    /**
     * 模拟soapUI调用WebService,解析返回报文
     * Created by PengHongfu 2018-04-26 15:36
     */
    public class TestSoap {
    
        //测试环境地址
        public static String INVOICE_WS_URL = "http://localhost:8082/*/webservices/**Service";
    
        public static void main(String[] args) throws Exception {
    
            String sid = "SID值";
            String content = "报文内容,jOSN格式";
            String tranSeq = "UUID";
            String tranReqDate = "2018-04-24";
            StringBuffer stringBuffer = testWebService(sid, content, tranSeq, tranReqDate);
    
            // 打印HTTP响应数据
            System.out.println(stringBuffer);
    
            //处理返回数据
            String xmlResult = stringBuffer.toString().replace("<", "<");
            String rtnCode = getXmlMessageByName(xmlResult, "rtnCode");//报文返回状态码,0表示正常,3表示错误
            String message = getXmlMessageByName(xmlResult, "message");//返回信息,主要是状态码不正常时抛出
            String body = getXmlMessageByName(xmlResult, "body");//返回正文数据,需要base64解密
            if ("0".equals(rtnCode)) {
                //查询成功
                if (StringUtils.isNotBlank(body)) {
                    //解密base64加密数据
                    Base64.Decoder decoder = Base64.getDecoder();
                    byte[] encodedText = body.getBytes();
                    String decrypt = new String(decoder.decode(encodedText), "UTF-8");
                    System.out.println(decrypt);
                }
            } else {
                //查询失败
            }
        }
    
        // 调用WS
        private static StringBuffer testWebService(String sid, String content, String tranSeq, String tranReqDate) throws Exception {
            //拼接请求报文
            String sendMsg = appendXmlContext(sid, content, tranSeq, tranReqDate);
            // 开启HTTP连接?
            InputStreamReader isr = null;
            BufferedReader inReader = null;
            StringBuffer result = null;
            OutputStream outObject = null;
            try {
                URL url = new URL(INVOICE_WS_URL);
                HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    
                // 设置HTTP请求相关信息
                httpConn.setRequestProperty("Content-Length",
                        String.valueOf(sendMsg.getBytes().length));
                httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
                httpConn.setRequestMethod("POST");
                httpConn.setDoOutput(true);
                httpConn.setDoInput(true);
    
                // 进行HTTP请求
                outObject = httpConn.getOutputStream();
                outObject.write(sendMsg.getBytes());
    
                if (200 != (httpConn.getResponseCode())) {
                    throw new Exception("HTTP Request is not success, Response code is " + httpConn.getResponseCode());
                }
                // 获取HTTP响应数据
                isr = new InputStreamReader(
                        httpConn.getInputStream(), "utf-8");
                inReader = new BufferedReader(isr);
                result = new StringBuffer();
                String inputLine;
                while ((inputLine = inReader.readLine()) != null) {
                    result.append(inputLine);
                }
                return result;
    
            } catch (IOException e) {
                throw e;
            } finally {
                // 关闭输入流
                if (inReader != null) {
                    inReader.close();
                }
                if (isr != null) {
                    isr.close();
                }
                // 关闭输出流
                if (outObject != null) {
                    outObject.close();
                }
            }
    
        }
    
        //拼接请求报文
        private static String appendXmlContext(String sid, String content, String tranSeq, String tranReqDate) {
            // 构建请求报文
    
            StringBuffer stringBuffer = new StringBuffer("<?xml version="1.0" encoding="utf-8"?>
    " +
                    "<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:com="http://com.foresee.top.service/">
    " +
                    "  <soapenv:Body>
    " +
                    "    <ns1:doService xmlns:ns1="http://cn.gov.chinatax.gt3nf.nfzcpt.service/">
    " +
                    "      <reqXml><![CDATA[<?xml version="1.0" encoding="utf-8"?>
    " +
                    "<tiripPackage xmlns:xsi="http://www.w3.org/2001/XMLSchema" version="1.0" xsi:type="tiripPackage">
    " +
                    "  <sessionId/>
    " +
                    "  <service>
    " +
                    "    <sid>" + sid + "</sid>
    " +         
                    "    <version>1.0</version>
    " +
                    "    <tranSeq>+" + tranSeq + "</tranSeq>
    " +
                    "    <tranReqDate>" + tranReqDate + "</tranReqDate>
    " +
                    "  </service>
    " +
                    "  <bizContent>
    " +
                    "    <content>" + content + "</content>
    " +
                    "    <paramList>
    " +
                    "      <param>
    " +
                    "        <name>docType</name>
    " +
                    "        <value>json</value>
    " +
                    "      </param>
    " +
                    "      <param>
    " +
                    "        <name>className</name>
    " +
                    "        <value>GGG</value>
    " +
                    "      </param>
    " +
                    "    </paramList>
    " +
                    "  </bizContent>
    " +
                    "</tiripPackage>
    " +
                    "]]></reqXml>
    " +
                    "    </ns1:doService>
    " +
                    "  </soapenv:Body>
    " +
                    "</soapenv:Envelope>");
            return stringBuffer.toString();
        }
    
        //解析报文,根据末节点名称获取值
        private static String getXmlMessageByName(String xmlResult, String nodeName) throws DocumentException {
            Document doc = DocumentHelper.parseText(xmlResult);
            DefaultXPath xPath = new DefaultXPath("//" + nodeName);
            xPath.setNamespaceURIs(Collections.singletonMap("ns1", "http://cn.gov.chinatax.gt3nf.nfzcpt.service/"));
            List list = xPath.selectNodes(doc);
            if (!list.isEmpty() && list.size() > 0) {
                Element node = (Element) list.get(0);
                return node.getText();
            }
            return "";
        }
    }
    

      

    针对下面的报文格式,取节点值:

    <?xml version="1.0" encoding="utf-8"?>
    
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">  
      <soap:Body> 
        <ns1:doServiceResponse xmlns:ns1="http://cn.gov.chinatax.gt3nf.nfzcpt.service/">  
          <return><![CDATA[<taxML><service><sid>SID值</sid><channelType>10</channelType><version>1.0</version><tranSeq>UUID</tranSeq><tranReqDate>20171204</tranReqDate></service><bizContent><bizResult><head><rtnCode>0</rtnCode><rtnMsg><code>000</code><message>处理成功</message><reason></reason></rtnMsg></head><body>PFJFU1BPTlNFX0NPT1k+(BASE64加密后的数据)</body></bizResult></bizContent><returnState><returnCode>00000</returnCode><returnMessage>Success!</returnMessage></returnState></taxML>]]></return> 
        </ns1:doServiceResponse> 
      </soap:Body> 
    </soap:Envelope>
    

      

  • 相关阅读:
    [LeetCode] Count and Say
    [LeetCode] Search Insert Position
    [LeetCode] Substring with Concatenation of All Words
    [LeetCode] Divide Two Integers
    笔记本清灰后组装后出现蓝屏,并不断的循环重新启动。
    自学MVC看这里——全网最全ASP.NET MVC 教程汇总
    sqlzoo练习答案--SELECT names/zh
    iOS Autolayout情况下,ViewController嵌套时,childViewController的Frame异常问题
    atitit. 文件上传带进度条 atiUP 设计 java c# php
    POJ 3237 Tree 树链剖分
  • 原文地址:https://www.cnblogs.com/achengmu/p/10057178.html
Copyright ? 2011-2022 开发猿


http://www.vxiaotou.com