Java调用CXF WebService接口的两种方式实例
方式一:使用CXF提供的工具生成客户端代码。
-
在项目中添加CXF的依赖。
-
使用CXF提供的命令行工具生成客户端代码,命令如下:
wsdl2java -d <output_dir> -p <package_name> <wsdl_url>
其中,<output_dir>
为生成的代码存放的目录,<package_name>
为生成的代码所在的包名,<wsdl_url>
为WebService的WSDL地址。
- 将生成的代码引入到项目中,然后就可以调用WebService接口了。例如:
HelloWorldService service = new HelloWorldService();
HelloWorldPortType port = service.getHelloWorldPort();
String result = port.sayHello("World");
System.out.println(result);
方式二:手动编写调用代码。
- 创建
JaxWsProxyFactoryBean
实例,并设置WebService的地址。
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setAddress(<wsdl_url>);
- 设置WebService接口的类。
factory.setServiceClass(HelloWorldPortType.class);
- 创建WebService接口的代理对象。
HelloWorldPortType port = (HelloWorldPortType) factory.create();
- 调用WebService接口的方法。
String result = port.sayHello("World");
System.out.println(result);
注意:以上代码中的HelloWorldPortType
为WebService接口的类名。具体的类名需要根据生成的客户端代码或者WebService的定义进行调整。