Android 中利用 ksoap2 调用 WebService的示例代码
去年刚刚工作的时候,第一个项目是要访问WebService。由于没有接触过,查了很多资料,在别人代码的基础上稍微修改了一下,总算满足了自己的需求。最近整理电脑的时候,发现了这个WebService的访问类,怕哪一天需要的时候找不到了,干脆写在博客上吧,也给需要的人提供一个参考。
1.下载ksoap2的jar文件
下载地址:ksoap2-android-assembly-3.6.1-jar-with-dependencies.jar
下载完成后依赖到自己的项目中即可。
2.封装网络访问工具类
直接贴代码了,注释写的很详细,根据自己的需要加以修改。
/** *访问WebService的工具类 */ publicclassWebServiceUtil{ //命名空间 privatestaticfinalStringNAMESPACE="yournamespace"; //WebService服务器地址 privatestaticfinalStringENDPOINT="youraddress"; //一般自己公司开发都是需要身份验证的 //身份验证方法名 privatestaticfinalStringID_HEADERNAME="verifymethod"; //身份验证key privatestaticfinalStringID_NAME_PARAM="verifykey1"; //身份验证value privatestaticfinalStringID_NAME_VALUE="verifyvalue1"; //身份验证key privatestaticfinalStringID_PASSWORD_PARAM="verifykey2"; //身份验证value privatestaticfinalStringID_PASSWORD_VALUE="verifyvalue2"; //访问的服务器是否由dotNet开发 publicstaticbooleanisDotNet=true; //线程池的大小 privatestaticintthreadSize=5; //创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程 privatestaticExecutorServicethreadPool=Executors.newFixedThreadPool(threadSize); //连接响应标示 publicstaticfinalintSUCCESS_FLAG=0; publicstaticfinalintERROR_FLAG=1; /** *调用WebService接口 * *@parammethodNameWebService的调用方法名 *@parammapParamsWebService的参数集合,可以为null *@paramreponseCallBack服务器响应接口 */ publicstaticvoidcall(finalStringmethodName,SimpleArrayMapmapParams,finalResponseCallBackreponseCallBack){ //创建HttpTransportSE对象,传递WebService服务器地址 finalHttpTransportSEtransport=newHttpTransportSE(ENDPOINT); transport.debug=true; //身份验证(如果需要的话) Element[]header=newElement[1]; //传入命名空间与验证的方法名 header[0]=newElement().createElement(NAMESPACE,ID_HEADERNAME); //创建参数1 ElementuserName=newElement().createElement(NAMESPACE,ID_NAME_PARAM); userName.addChild(Node.TEXT,ID_NAME_VALUE); header[0].addChild(Node.ELEMENT,userName); //创建参数2 Elementpassword=newElement().createElement(NAMESPACE,ID_PASSWORD_PARAM); password.addChild(Node.TEXT,ID_PASSWORD_VALUE); header[0].addChild(Node.ELEMENT,password); //创建SoapObject对象用于传递请求参数 finalSoapObjectsoapObject=newSoapObject(NAMESPACE,methodName); //添加参数 if(mapParams!=null){ for(intindex=0;index 3.在Activity中使用
privatevoidrequest(){ SimpleArrayMapmap=newSimpleArrayMap<>(); map.put("key1","value1"); map.put("key2","value2"); WebServiceUtil.call("methodname",map,newWebServiceUtil.ResponseCallBack(){ @Override publicvoidonSuccess(Stringresult){ //请求成功 } @Override publicvoidonError(Exceptione){ //请求失败 } }); } 至此调用结束,有需要访问WebService的同学可以参考一下。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。