SOAP XML发送请求及解析返回的XML

导包

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

go

利用SoapUI看看请求xml的格式
在这里插入图片描述

创建工具类,在SoapUtil.SplicingMessage()里面拼接参数并替换图片中的?

package com.common;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import javax.xml.soap.*;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

/**
 * Soap工具类
 *
 * @author XianYao
 * @version V1.0.0
 * @date 2022/3/8 15:40
 */
public class SoapUtil {
    public static void main(String[] args) {
        String xmlStr = "<Service>" +
                "<RegionCode>991</RegionCode>" +
                "<Word>嘉华园</Word>" +
                "<AccType></AccType>" +
                "<PageSize>10</PageSize>" +
                "<PageIndex>1</PageIndex>" +
                "</Service>";
        //webService接口地址
        String postUrl = "http://123.456.789:1234/ResWebservice/services/NewAddrService";
        //"http://tempuri.org/execute";
        String soapAction = "";
        //访问接口
        String result = SoapUtil.SplicingMessage(xmlStr, postUrl, soapAction, "searchAddr", "ns1:searchAddrResponse", "searchAddrReturn");
        System.out.println("返回的数据为:" + result);
    }

    /**
     * 访问webservice接口
     *
     * @param postUrl    webService接口地址
     * @param soapAction soapAction地址
     * @param method     方法名
     * @param node       节点
     * @param childNode  子节点
     * @return 返回值
     */
    public static String SplicingMessage(String xmlBodyStr, String postUrl, String soapAction, String method, String node, String childNode) {
        //自定义soap报文模板
        String xmlStr = "<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:addr=\"http://addr.webservice.ztesoft.com\">" +
                "   <soapenv:Header/>" +
                "   <soapenv:Body>" +
                "      <addr:" + method + " soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" +
                "         <xml xsi:type=\"xsd:string\">" +
                "          <![CDATA[" + xmlBodyStr + "]]>" +
                "         </xml>" +
                "      </addr:" + method + ">" +
                "   </soapenv:Body>" +
                "</soapenv:Envelope>";

        System.out.println("自定义soap报文模板 ===> " + xmlStr);
        return doPostSoap(postUrl, xmlStr, soapAction, node, childNode);
    }

    /**
     * 使用SOAP发送消息
     *
     * @param postUrl    webService接口地址
     * @param soapXml    请求体
     * @param soapAction soapAction
     */
    public static String doPostSoap(String postUrl, String soapXml, String soapAction, String node, String childNode) {
        String retStr = "";
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(postUrl);
        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().build();
        httpPost.setConfig(requestConfig);
        try {
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
            httpPost.setHeader("SOAPAction", soapAction);
            StringEntity data = new StringEntity(soapXml, StandardCharsets.UTF_8);
            httpPost.setEntity(data);
            CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                // 打印响应内容
                retStr = EntityUtils.toString(httpEntity);
                System.out.println("soap响应内容 ===> " + retStr);
            }
            // 释放资源
            closeableHttpClient.close();
        } catch (Exception e) {
            
        }
        return soapXmlToBean(retStr, node, childNode);
    }

    /**
     * @param soapXml 请求结果string
     * @return 请求结果
     */
    public static String soapXmlToBean(String soapXml, String node, String childNode) {
        Iterator<SOAPElement> iterator = null;
        String res = "";
        try {
            //javax.xml.soap类MessageFactory
            MessageFactory msgFactory = MessageFactory.newInstance();
            //创建一个soapMessage对象
            SOAPMessage reqMsg = msgFactory.createMessage(new MimeHeaders(),
                    new ByteArrayInputStream(soapXml.getBytes(StandardCharsets.UTF_8)));
            reqMsg.saveChanges();
            //取出soapBody对象
            SOAPBody body = reqMsg.getSOAPBody();
            //遍历子节点
            iterator = body.getChildElements();
        } catch (Exception e) {
            e.printStackTrace();
        }
        while (iterator.hasNext()) {
            SOAPElement element = iterator.next();
            System.out.println("节点名称---:" + element.getNodeName());
            if (node.equals(element.getNodeName())) {
                Iterator<SOAPElement> it = element.getChildElements();
                SOAPElement el = null;
                while (it.hasNext()) {
                    el = it.next();
                    //取到content子节点的值
                    if (childNode.equals(el.getNodeName())) {
                        System.out.println("子节点值---:" + el.getValue());
                        res = el.getValue();
                        break;
                    }
                }
                break;
            }
        }
        return res;
    }
}



拼接完成后的请求参数
在这里插入图片描述

在SoapUI里面测试一下,searchAddrReturn标签里面包裹的就是请求的数据,然后再调用SoapUtil.soapXmlToBeanok()把数据提出来,更完美的写法可以参考这个【链接
在这里插入图片描述

参考链接

https://blog.csdn.net/zz18435842675/article/details/96869484
https://blog.csdn.net/zz_lk_xx/article/details/84978699

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值