客戶端調用web service方法
首先要使用cxf的wsdl2java命令工具生成服務代理類,如:
wsdl2java -d E:\\zengyf\\download -all http://124.89.118.212:13000/as_mas/WS/SMPlatform?wsdl
具體命令格式可使用wsdl2java /?查看。生成后的代理類名是:服務實現類名+Service
方法一:使用標准的JAX-WS的API完成客戶端調用
//注意。此處http:http://www.itfad.net/queryUser是服務的命名空間,可查看wsdl文件中的targetNamespace
QName qName = new QName("http://www.itfad.net/queryUser","QueryUserImplService");
QueryUserImplService ImplService =new QueryUserImplService(new URL("http://localhost:8080/CXFDemo/queryUser?wsdl"),qName);
IQueryUser service=(IQueryUser)ImplService.getPort(IQueryUser.class);
方法二:javax.xml.ws.Service
String endPointAddress = "http://localhost:8080/queryUser";//服務實際地址
//此處http://charles.com/為命名空間,默認是包名的倒序。IQueryUserService=服務接口名+service
javax.xml.ws.Service service = javax.xml.ws.Service.create(new QName("http://charles.com/","IQueryUserService"));
//IQueryUserPort=服務接口名+Port
service.addPort(new QName("http://charles.com/","IQueryUserPort"),javax.xml.ws.soap.SOAPBinding.SOAP11HTTP_BINDING, endPointAddress);
IQueryUser queryService1 =service.getPort(IQueryUser.class);
System.out.println(queryService1.query(user));
這里其實利用wsdl2java工具為我們生成類時已經包含了這種方法。比如我們的服務接口是IQueryUser,那么我們會發現生成的文件下有個IQueryUserService類
該類正是繼承至javax.xml.ws.Service,並封裝以上代碼的功能,調用代碼如下:
IQueryUserService queryUserService=new IQueryUserService();//默認構造函數里使用默認wsdl地址和服務的QName
IQueryUser queryService1 =queryUserService.getIQueryUserPort();//方法內部調用了super.getPort(IQueryUserPort, IQueryUser.class);
System.out.println(queryService1.query(user));
方法三:使用CXF中JaxWsProxyFactoryBean客戶端代理工廠調用web服務
JaxWsProxyFactoryBean soapFactoryBean = newJaxWsProxyFactoryBean();
soapFactoryBean.setAddress("http://localhost:8080/queryUser");
soapFactoryBean.setServiceClass(IQueryUser.class);
Object o = soapFactoryBean.create();
IQueryUser service = (IQueryUser)o;
方法四:使用CXF的JaxWsDynamicClientFactory動態代理工廠
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
Client client = dcf.createClient("people.wsdl", classLoader);
Object person =Thread.currentThread().getContextClassLoader().loadClass("com.acme.Person").newInstance();
Method m = person.getClass().getMethod("setName", String.class);
m.invoke(person, "Joe Schmoe");
client.invoke("addPerson", person);
針對SOAP12實現的服務,采用(建議SOAP11也采用該調用,比上述動態要有效率):
String http="http://127.0.0.1:8080/as_mas/WS/SMPlatform?wsdl";
JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
QName SERVICE = new QName(targetNamespace, wsdl:service.name);
QName MASPort = new QName(targetNamespace, wsdl:port.name);
Client client = factory.createClient(http, SERVICE, MASPort);
Object[] result;
System.out.println("success>>>>>>>>>>>>>>");
String method1="receiveTextMsg";
try {
result = client.invoke(method1,"test","test","134123","123");
System.out.println(result[0]);
} catch (Exception e) {
e.printStackTrace();
}
