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
- 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>
- Construct the SOAP request according to the corresponding content in SoapUI.
We know that:
- The method name is:
web:getCountryCityByIp
- There is only one parameter, which is:
web:theIpAddress
- A namespace is defined, with the prefix
web
and the URIhttp://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