SoapClient

Origin

WebService interfaces occupy a large share in interface integration, and in order to use these interfaces, we have to introduce libraries such as Axis to implement interface requests.

Now with Hutool, we can implement simple WebService requests without any dependencies.

Usage

  1. Use SoapUI to parse the WSDL address and find the WebService method and parameters.

The XML template we obtained is:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://WebXml.com.cn/">
   <soapenv:Header/>
   <soapenv:Body>
      <web:getCountryCityByIp>
         <!--Optional:-->
         <web:theIpAddress>?</web:theIpAddress>
      </web:getCountryCityByIp>
   </soapenv:Body>
</soapenv:Envelope>
  1. Construct the SOAP request according to the corresponding content in SoapUI.

We know that:

  1. The method name is: web:getCountryCityByIp
  2. There is only one parameter, which is: web:theIpAddress
  3. A namespace is defined, with the prefix web and the URI http://WebXml.com.cn/

So we can construct the corresponding SOAP request as follows:

// Create a new client
SoapClient client = SoapClient.create("http://www.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx")
    // Set the method to be requested, with the prefix of this interface method as web and the corresponding namespace
    .setMethod("web:getCountryCityByIp", "http://WebXml.com.cn/")
    // Set the parameter, where the prefix of the method is automatically added: web
    .setParam("theIpAddress", "218.21.240.106");

    // Send the request, with the parameter true indicating to return a formatted XML content
    // The return content is an XML string, which can be parsed with XmlUtil
    Console.log(client.send(true));

Extensions

Viewing the generated request XML

The getMsgStr method of the SoapClient object can be called to view the generated XML, in order to check whether it is consistent with that generated by SoapUI.

SoapClient client = ...;
Console.log(client.getMsgStr(true));

Multiple parameters or complex parameters

For cases where the request body is a list parameter or multiple parameters, such as:

<web:method>
  <arg0>
    <fd1>aaa</fd1>
    <fd2>bbb</fd2>
  </arg0>
</web:method>

Such requests can be made with the help of addChildElement.

SoapClient client = SoapClient.create("https://hutool.cn/WebServices/test.asmx")
        .setMethod("web:method", "http://hutool.cn/")
        SOAPElement arg0 = client.getMethodEle().addChildElement("arg0");
        arg0.addChildElement("fdSource").setValue("?");
        arg0.addChildElement("fdTemplated").setValue("?");

For detailed problem solutions, see: https://gitee.com/dromara/hutool/issues/I4QL1V