JAVA调用WSDL接口
1. 使用Apache CXF工具调用
1.1. MAVEN引用
<!-- cxf -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.1.10</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>3.1.10</version>
</dependency>
1.2. 接口调用程序示例
package com.wzl.test;
import com.alibaba.fastjson.JSON;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
public class Wsdl {
public static void main(String[] args) throws Exception {
// 创建JaxWsDynamicClientFactory工厂
JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
// 创建Client对象
Client client = factory.createClient("http://localhost:8008/test.asmx?WSDL");
// 调用方法
Object[] results = client.invoke("方法名", "参数1", "参数2");
//输出返回结果
System.out.println(JSON.toJSONString(results));
}
}
2. 使用Hutool工具的SOAPClient调用
相比Apache CXF的调用方式更灵活,能够根据自己的需要组装XML请求,如果CXF方式调用不适用的情况下,可以考虑此方法,除此之外还有axis的方法调用(此处不做介绍)。
2.1. MAVEN引用
<!-- hutool(此处引用全部,可以按需引用) -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
2.2. 接口调用程序示例
package com.wzl.test;
import cn.hutool.http.webservice.SoapClient;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
public class WsdlSoap {
public static void main(String[] args) throws SOAPException {
// 创建SoapClient实例
SoapClient client = SoapClient.create("http://localhost:8008/test.asmx?WSDL")
// 设置方法名和命名空间(web:命名空间,test:方法名,没有命名空间时直接写方法名即可)
.setMethod("web:test", "http://service.webservice.adcc.com/")
// 设置参数(最后的false参数表示参数不加命名空间的前缀web)
.setParam("username", "admin", false)
.setParam("password", "admin", false);
// 获取SOAPMessage实例(此步作用是输出请求的XML参数,实际开发并不需要)
SOAPMessage message = client.getMessage();
System.out.println(client.getMsgStr(true));
// 发送请求(true表示输出的结果格式化处理)
String send = client.send(true);
System.out.println(send);
}
}
上面示例输出的请求XML如下:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<web:test xmlns:web="http://service.webservice.adcc.com/">
<username>admin</username>
<password>admin</password>
</web:test>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>