java 如何读取wsdl
读取 WSDL 文件的方法
在 Java 中读取 WSDL 文件通常涉及使用 SOAP 相关的库或工具。以下是几种常见的方法:
使用 Apache CXF 动态生成客户端
Apache CXF 是一个开源的 Web 服务框架,可以用于动态生成客户端代码并解析 WSDL。
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
public class WSDLReader {
public static void main(String[] args) throws Exception {
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
String wsdlUrl = "http://example.com/service?wsdl";
Client client = dcf.createClient(wsdlUrl);
// 调用服务方法
Object[] result = client.invoke("methodName", "param1", "param2");
System.out.println(result[0]);
}
}
使用 JAX-WS 生成客户端
JAX-WS 是 Java 自带的 Web 服务 API,可以通过 wsimport 工具生成客户端代码。

-
使用命令行生成客户端代码:
wsimport -keep http://example.com/service?wsdl -
在代码中调用生成的客户端:

import com.example.Service; import com.example.ServicePortType;
public class WSDLReader { public static void main(String[] args) { Service service = new Service(); ServicePortType port = service.getServicePort();
String result = port.methodName("param1", "param2");
System.out.println(result);
}
}
#### 使用 DOM 解析 WSDL 文件
如果需要手动解析 WSDL 文件,可以使用 DOM 或 SAX 解析器。
```java
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class WSDLReader {
public static void main(String[] args) throws Exception {
String wsdlUrl = "http://example.com/service?wsdl";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(wsdlUrl);
NodeList services = document.getElementsByTagName("wsdl:service");
for (int i = 0; i < services.getLength(); i++) {
System.out.println("Service: " + services.item(i).getAttributes().getNamedItem("name").getNodeValue());
}
}
}
使用第三方库如 WSDL4J
WSDL4J 是一个专门用于解析 WSDL 文件的库。
import javax.wsdl.*;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
public class WSDLReader {
public static void main(String[] args) throws Exception {
WSDLFactory factory = WSDLFactory.newInstance();
WSDLReader reader = factory.newWSDLReader();
Definition definition = reader.readWSDL("http://example.com/service?wsdl");
Map services = definition.getServices();
services.forEach((key, value) -> System.out.println("Service: " + key));
}
}
注意事项
- 确保 WSDL 文件的 URL 可访问或本地路径正确。
- 如果使用动态生成客户端的方法,注意处理网络异常和超时问题。
- 对于复杂的 WSDL 文件,可能需要手动解析命名空间和类型定义。
以上方法可以根据具体需求选择,动态生成客户端适合快速开发,而手动解析适合需要深度定制的情况。






