如需要在项目中调用WebService服务,则需要做以下工作(在此以天气预报服务http://www.webservicex.net/globalweather.asmx为例)
一、在需要调用webservice的项目中添加cxf的依赖(http://cxf.apache.org/download.html)
二、通过wsdl文件生成客户端调用service的接口(GlobalWeatherSoap)
生成方法
1、打开cxf的完整目录
2、命令行中通过cd切换到这个目录(apache-cxf-2.7.x\bin)
3、执行命令
wsdl2java http://www.webservicex.net/globalweather.asmx?WSDL
注:把http://www.webservicex.net/globalweather.asmx?WSDL 换成相应的wsdl地址
三、通过以下方式调用远程方法
String address = "http://www.webservicex.net/globalweather.asmx"; //此处最好用系统参数
JaxWsProxyFactoryBean bean = new JaxWsProxyFactoryBean();
bean.setAddress(address);
bean.setServiceClass(GlobalWeatherSoap.class);
GlobalWeatherSoap ws = (GlobalWeatherSoap) bean.create();
System.out.println(ws.getCitiesByCountry("China"));
System.out.println(ws.getWeather("Shanghai", "China"));
注:要把GlobalWeatherSoap换成我们第二步成成的接口Service
四、也可以通过Spring来配置客户端
<import resource="classpath:META-INF/cxf/cxf.xml" /> <jaxws:client id="globalWeatherSoap" serviceClass="net.webservicex.GlobalWeatherSoap" address="http://www.webservicex.net/globalweather.asmx"/>
(注意要在spring的beans.xml中添加命名空间如下)
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
然后通过以下代码调用
@Autowired
GlobalWeatherSoap soap; //注入上面定义的接口
@Test
public void testSoapCall() {
String result = soap.getCitiesByCountry("China");//直接调用接口中的方法
System.out.println( result );
}