当时用这个主要是为了 解决cxf连接webservice的 undefined element declaration s:schema 错误,然后自己弄了一个工具类出来,方便使用。
第一步:加入axis2的依赖
pom.xml
<!-- axis2 -->
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-spring</artifactId>
<version>1.7.8</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-transport-http</artifactId>
<version>1.7.8</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-transport-local</artifactId>
<version>1.7.8</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-xmlbeans</artifactId>
<version>1.7.8</version>
</dependency>
<dependency>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-api</artifactId>
<version>1.2.20</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-jaxws</artifactId>
<version>1.7.8</version>
</dependency>
第二步:创建自定义工具类
Axis2ClientUtils.java
/**
* axis2调用webservice工具类
*
* @author lwx
* @since 2022-09-16
*/
public class Axis2ClientUtils {
/**
* 使用axis2调用webservice
* @param url wsdl地址
* @param targetNamespace soap命名空间
* @param method 目标方法
* @param params [参数名,参数值,参数名1,参数值1,...] 参数集合
* @return 调用结果
* @throws AxisFault
*/
public static String invokeAxis2Server(String url, String targetNamespace, String method, Object... params) throws AxisFault {
ServiceClient serviceClient = new ServiceClient();
Options options = serviceClient.getOptions();
// 指定调用WebService的URL
EndpointReference targetEPR = new EndpointReference(url);
options.setTo(targetEPR);
// 确定调用方法
options.setAction(targetNamespace + method);
OMFactory fac = OMAbstractFactory.getOMFactory();
// 指定命名空间
OMNamespace omNs = fac.createOMNamespace(targetNamespace, "");
// 指定方法
OMElement methodElement = fac.createOMElement(method, omNs);
//为方法指定参数
for (int i = 0; i < params.length; i=i+2) {
OMElement theRegionCode = fac.createOMElement(String.valueOf(params[i]), omNs);
theRegionCode.setText(String.valueOf(params[i+1]));
methodElement.addChild(theRegionCode);
}
methodElement.build();
//远程调用web服务
OMElement omElement = serviceClient.sendReceive(methodElement);
// 结果集(根据情况修改)
/*String result = null;
Iterator childElements = omElement.getChildElements();
while (childElements.hasNext()) {
OMElement elem = (OMElement) childElements.next();
result = elem.getText();
}*/
String result = omElement.getFirstElement().toString();
return result;
}
}
第三步:调用方法
String url = ""; // webservice接口地址,不带?wsdl
String targetNamespace = ""; // 接口文档的targetNamespace
String method = ""; // webservice方法名
String paramName = ""; // webservice接口参数的参数名
String param = ""; // webservice接口参数
try {
String result = Axis2ClientUtils.invokeAxis2Server(url, targetNamespace, method, paramName, param);
// todo 处理返回的xml字符串:result
} catch (Exception e) {
e.printStackTrace();
}