实现PRC调用WebService的客户端程序
??? WebService是为程序服务的,只在浏览器中访问WebService是没有意义的。因此,在本节使用Java实现了一个控制台程序来调用上一节发布的WebService。调用WebService的客户端代码如下:
package
?client;
import ?javax.xml.namespace.QName; import ?org.apache.axis2.addressing.EndpointReference; import ?org.apache.axis2.client.Options; import ?org.apache.axis2.rpc.client.RPCServiceClient; public ? class ?RPCClient { ???? public ? static ? void ?main(String[]?args)? throws ?Exception?? ????{ ???????? // ??使用RPC方式调用WebService???????? ????????RPCServiceClient?serviceClient? = ? new ?RPCServiceClient(); ????????Options?options? = ?serviceClient.getOptions(); ???????? // ??指定调用WebService的URL ????????EndpointReference?targetEPR? = ? new ?EndpointReference( ???????????????? " http://localhost:8080/axis2/services/SimpleService " ); ????????options.setTo(targetEPR); ???????? // ??指定getGreeting方法的参数值 ????????Object[]?opAddEntryArgs? = ? new ?Object[]?{ " 超人 " }; ???????? // ??指定getGreeting方法返回值的数据类型的Class对象 ????????Class[]?classes? = ? new ?Class[]?{String. class }; ???????? // ??指定要调用的getGreeting方法及WSDL文件的命名空间 ????????QName?opAddEntry? = ? new ?QName( " http://ws.apache.org/axis2 " ,? " getGreeting " ); ???????? // ??调用getGreeting方法并输出该方法的返回值 ????????System.out.println(serviceClient.invokeBlocking(opAddEntry,?opAddEntryArgs,?classes)[ 0 ]); ???????? // ??下面是调用getPrice方法的代码,这些代码与调用getGreeting方法的代码类似 ????????classes? = ? new ?Class[]?{ int . class }; ????????opAddEntry? = ? new ?QName( " http://ws.apache.org/axis2 " ,? " getPrice " ); ????????System.out.println(serviceClient.invokeBlocking(opAddEntry,? new ?Object[]{},?classes)[ 0 ]); ????}? } ? ? ? ? 运行上面的程序后,将在控制台输出如下的信息: ?
你好?超人
443 ??? 在编写客户端代码时应注意如下几点: ??? 1.?客户端代码需要引用很多Axis2的jar包,如果读者不太清楚要引用哪个jar包,可以在Eclipse的工程中引用Axis2发行包的lib目录中的所有jar包。 ??? 2.?在本例中使用了RPCServiceClient类的invokeBlocking方法调用了WebService中的方法。invokeBlocking方法有三个参数,其中第一个参数的类型是QName对象,表示要调用的方法名;第二个参数表示要调用的WebService方法的参数值,参数类型为Object[];第三个参数表示WebService方法的返回值类型的Class对象,参数类型为Class[]。当方法没有参数时,invokeBlocking方法的第二个参数值不能是null,而要使用new Object[]{}。 ??? 3.?如果被调用的WebService方法没有返回值,应使用RPCServiceClient类的invokeRobust方法,该方法只有两个参数,它们的含义与invokeBlocking方法的前两个参数的含义相同。 ??? 4.?在创建QName对象时,QName类的构造方法的第一个参数表示WSDL文件的命名空间名,也就是<wsdl:definitions>元素的targetNamespace属性值,下面是SimpleService类生成的WSDL文件的代码片段:
<?
xml?version="1.0"?encoding="UTF-8"
?>
< wsdl:definitions? xmlns:wsdl ="http://schemas.xmlsoap.org/wsdl/" ?xmlns:ns1 ="http://org.apache.axis2/xsd" xmlns:ns ="http://ws.apache.org/axis2" ?xmlns:wsaw ="http://www.w3.org/2006/05/addressing/wsdl" xmlns:http ="http://schemas.xmlsoap.org/wsdl/http/" ?xmlns:xs ="http://www.w3.org/2001/XMLSchema" xmlns:mime ="http://schemas.xmlsoap.org/wsdl/mime/" ?xmlns:soap ="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soap12 ="http://schemas.xmlsoap.org/wsdl/soap12/" targetNamespace="http://ws.apache.org/axis2" > ???? < wsdl:types > ????????? ???? </ wsdl:types > ????? </ wsdl:definitions > (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |