JAVA調用WebService

   最近項目中需要其他系統的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);
	}
}



發佈了21 篇原創文章 · 獲贊 12 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章