最近项目中需要其他系统的WebService,以前都是直接调用HTTP,然后自己找了如下方法调用,也是对自己学习的一点笔记。工程需要依赖apache的包,下载地址:http://download.csdn.net/detail/zhangyong125/9169431
代码如下:
第一个是调用工具类:
import java.rmi.RemoteException;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceException;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
public class WebServiceUtil {
/**
* 远程调用WebService接口
* 参数可通过如http://localhost:8060/WebService/tes/HRWebServiceForLandray.asmx
*
* @param parameters 接口需要的参数名数组
* @param parametersValue 接口需要的参数所对应的参数值数组
* @param operationName 调用接口所对应的方法
* @param namespaceURI WebService默认命名空间
* @param endpoint WebService服务地址
* @return jsonStr
*/
public static String callWebService(String[] parameters, Object[] parametersValue,
String operationName, String namespaceURI, String endpoint) {
final String soapActionURI = namespaceURI + operationName;
String result = "no result!";
Service service = new Service();
Call call;
try {
call = (Call) service.createCall();
call.setTargetEndpointAddress(endpoint);// 远程调用路径
call.setSOAPActionURI(soapActionURI);
call.setOperationName(new QName(namespaceURI, operationName));
for (int i = 0; i < parameters.length; i++) {
call.addParameter(new QName(namespaceURI, parameters[i]), XMLType.SOAP_STRING, ParameterMode.IN);
}
call.setReturnType(XMLType.SOAP_STRING);// 返回值类型:String
result = (String) call.invoke(parametersValue);// 远程调用,获取json串
} catch (ServiceException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
return result;
}
}
第二个是测试类:
public class WebService {
public static String endpoint = "http://localhost8060/test.asmx";
public static String namespaceURI = "http://tempuri.org/";
public static String key="809809808089800809";
public static void main(String[] args) {
String[] parameters = {"strJson", "strLoginAccount", "strVerifyCode", "strType"};
Object[] parametersValue = {"1989898989", "17627363727",key, "im"};
String result = WebServiceUtil.callWebService(parameters, parametersValue, "UpdateMoblie", namespaceURI, endpoint);
System.out.println(result);
}
}