参考:http://www.cnblogs.com/xwdreamer/archive/2011/12/07/2296914.html
http://cxshun.iteye.com/blog/1275408
去官网下载包WebService所需要的包:http://axis.apache.org/axis2/java/core/modules/index.html
配置WebService所在的包
新建一个动态web工程
代码如下:
package main;
/**
* 计算器运算
*
*/
public class CalculateService {
// 加法
public float plus(float x, float y) {
return x + y;
}
// 减法
public float minus(float x, float y) {
return x - y;
}
// 乘法
public float multiply(float x, float y) {
return x * y;
}
// 除法
public float divide(float x, float y) {
if (y != 0) {
return x / y;
} else
return -1;
}
}
新建一个WebService
会自动生成:
我们新建一个MyWebServiceTest.java,代码如下:
package main;
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 MyWebServiceTest {
/**
* @param args
* @throws AxisFault
*/
public static void main(String[] args) throws AxisFault {
// TODO Auto-generated method stub
// 使用RPC方式调用WebService
RPCServiceClient serviceClient = new RPCServiceClient();
Options options = serviceClient.getOptions();
// 指定调用WebService的URL
EndpointReference targetEPR = new EndpointReference(
"http://localhost:8080/MyWebService/services/CalculateService");
options.setTo(targetEPR);
// 指定要调用的计算机器中的方法及WSDL文件的命名空间:main
QName opAddEntry = new QName("http://main", "plus");// 加法
QName opAddEntryminus = new QName("http://main", "minus");// 减法
QName opAddEntrymultiply = new QName("http://main", "multiply");// 乘法
QName opAddEntrydivide = new QName("http://main", "divide");// 除法
// 指定plus方法的参数值为两个,分别是加数和被加数
Object[] opAddEntryArgs = new Object[] { 1, 2 };
// 指定plus方法返回值的数据类型的Class对象
Class[] classes = new Class[] { float.class };
// 调用plus方法并输出该方法的返回值
System.out.println(serviceClient.invokeBlocking(opAddEntry, opAddEntryArgs, classes)[0]);
System.out.println(serviceClient.invokeBlocking(opAddEntryminus, opAddEntryArgs, classes)[0]);
System.out.println(serviceClient.invokeBlocking(opAddEntrymultiply, opAddEntryArgs, classes)[0]);
System.out.println(serviceClient.invokeBlocking(opAddEntrydivide, opAddEntryArgs, classes)[0]);
}
}
运行下上段代码就会出结果,如果程序报错,应该是对应的http://main改成自己的WSDL文件的命名空间,或者导入所需要的包,包在axis2-1.6.3\lib目录下。