原因
在项目对接过程中,有好多老项目的接口还是webservice接口,就导致需要使用这些接口是还要映入Axis库,现在有hutool工具库的存在,只需要引入hutool就可以完成对webservice接口的调用,下面是在一个项目中的使用记录一下
1. 引入Hutool依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.4</version>
</dependency>
2. 使用
示例1
xml数据
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webservice.com/">
<soapenv:Header/>
<soapenv:Body>
<web:getCountryCityByIp>
<!--Optional:-->
<arg0>192.168.0.2</arg0>
</web:getCountryCityByIp>
</soapenv:Body>
</soapenv:Envelope>
代码构建soap请求
private static void sendWebservice() throws SOAPException {
String authenticationUrl = "http://xxx?wsdl";
QName qname = new QName("RequestSOAPHeader");
SoapClient soapClient = SoapClient.create(authenticationUrl)
.setMethod("web:getCountryCityByIp","http://webservice.com/")
.setParam("arg0","192.168.0.2",false);
//设置请求头参数
SOAPHeaderElement soapHeaderElement = soapClient.addSOAPHeader(qname);
SOAPElement user = soapHeaderElement.addChildElement("user");
//账号
user.setTextContent("oa");
SOAPElement password = soapHeaderElement.addChildElement("password");
//密码
password.setTextContent("bdf01990300ed0d0a306428");
//发送请求
String result = soapClient.send(true);
System.out.println(result);
Document document = XmlUtil.parseXml(result);
NodeList aReturn = document.getElementsByTagName("return");
for (int i = 0; i < aReturn.getLength(); i++) {
Node node = aReturn.item(i);
Map<String, Object> map = XmlUtil.xmlToMap(node);
System.out.println(map);
}
}
示例2
xml数据增加SOAPHeader
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webservice.com/">
<soapenv:Header/>
<RequestSOAPHeader>
<user>zs</user>
</RequestSOAPHeader>
<soapenv:Body>
<web:getCountryCityByIp>
<!--Optional:-->
<arg0>192.168.0.2</arg0>
</web:getCountryCityByIp>
</soapenv:Body>
</soapenv:Envelope>
private static void sendWebservice() throws SOAPException {
String authenticationUrl = "http://xxx?wsdl";
QName qname = new QName("http://sys.webservice.client/","RequestSOAPHeader");
SoapClient soapClient = SoapClient.create(authenticationUrl)
.setMethod("web:getCountryCityByIp","http://webservice.com/")
.setParam("arg0","192.168.0.2",false)
SOAPHeaderElement soapHeaderElement = soapClient.addSOAPHeader(qname);
SOAPElement user = soapHeaderElement.addChildElement("user");
//账号
user.setTextContent("zs");
String result = soapClient.send(true);
System.out.println(result);
Document document = XmlUtil.parseXml(result);
NodeList aReturn = document.getElementsByTagName("return");
for (int i = 0; i < aReturn.getLength(); i++) {
Node node = aReturn.item(i);
Map<String, Object> map = XmlUtil.xmlToMap(node);
System.out.println(map);
}
}