上一篇,记录了通过axis2创建发布web service服务,这一篇将记录,如何通过 axis2调用web service 接口,目前找到两种方法,这一篇先介绍其中一种方法,下一篇介绍另一种方法:
通过 axis2调用web service方法一:不采用stub方式
1、新建一个java project,将 axis2/lib 下所有的包都添加进来(由于包较多,可以建一个 user library 将这些包放一起 )
2、建包,建类,源码如下:
- package wsclient;
- import javax.xml.namespace.QName;
- import org.apache.axis2.AxisFault;
- import org.apache.axis2.addressing.EndpointReference;
- import org.apache.axis2.client.Options;
- import org.apache.axis2.rpc.client.RPCServiceClient;
- public class HelloClient {
- private RPCServiceClient serviceClient;
- private Options options;
- private EndpointReference targetEPR;
- public HelloClient(String endpoint) throws AxisFault {
- serviceClient = new RPCServiceClient();
- options = serviceClient.getOptions();
- targetEPR = new EndpointReference(endpoint);
- options.setTo(targetEPR);
- }
- public Object[] invokeOp(String targetNamespace, String opName,Object[] opArgs, Class<?>[] opReturnType) throws AxisFault,ClassNotFoundException {
- // 设定操作的名称
- QName opQName = new QName(targetNamespace, opName);
- // 设定返回值
- // Class<?>[] opReturn = new Class[] { opReturnType };
- // 操作需要传入的参数已经在参数中给定,这里直接传入方法中调用
- return serviceClient.invokeBlocking(opQName, opArgs, opReturnType);
- }
- public static void main(String[] args) throws AxisFault,
- ClassNotFoundException {
- // TODO Auto-generated method stub
- final String endPointReference = "http://localhost:8080/axis2/services/Hello";
- final String targetNamespace = "http://ws";
- HelloClient client = new HelloClient(endPointReference);
- String opName = "sayHello";
- Object[] opArgs = new Object[] { "tester" };
- Class<?>[] opReturnType = new Class[] { String[].class };
- Object[] response = client.invokeOp(targetNamespace, opName, opArgs,opReturnType);
- System.out.println(((String[]) response[0])[0]);
- }
- }
3、运行,打印出:Hello,tester
则说明调用成功!
注:上述代码来自:http://blog.sina.com.cn/s/blog_5cef6d430100jr4f.html