android web services2

Android中调用Web Services有很多方法,我们现在使用的是ksoap ,它是SOAP web services的客户端包,ksoap现在版本为2.0.它的一个主要优点就是对dotNET兼容性比较不错。

首先下载ksoap的包文件(下载地址 ),在Eclispe的Package Explorer中右键项目,Build Path>Add Libraries,找到ksoap2-android-assembly-2.4-jar-with-dependencies.jar添加该引用。代码如下:

public class WSHelper {
     final static String WSUrl= "http://xxx/WSUrl.asmx " ;
 
     private static String namespace = "http://tempuri.org/ " ;
     /*************************************
      * 获取web services内容
      * @param url
      * @param params
      * @return
      *************************************/
     public static String GetResponse(String method,List<BasicNameValuePair> params){
          
         try {
             String url = WSUrl;
             SoapObject request = new SoapObject(namespace, method);
             for ( int i= 0 ,len=params.size();i<len;i++){
                 request.addProperty(params.get(i).getName(), params.get(i).getValue());
             }
             SoapSerializationEnvelope envelope =
                 new SoapSerializationEnvelope(SoapEnvelope.VER11);
             envelope.dotNet = true ;
             envelope.setOutputSoapObject(request);
              
             AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(url);
             androidHttpTransport.call(namespace + method, envelope);
              
             SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
             return result.toString();
         } catch (Exception e) {
             return "Error:calling the web services error" ;
         }
     }
}

调用时代码如下:

String method = "MethodName" ; //方法名称
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add( new BasicNameValuePair( "userId" , String.valueOf( 1995 )));
return WSHelper.GetResponse(method,params);

 这里参数可以定义多个,返回时是以String类似来返回。

注意由于我们调用Web sevices,就需要程序有访问网络的权限,因此需要在AndroidManifest.xml中manifest节中增加访问网络权限的定义:

< uses-permission android:name = "android.permission.INTERNET" ></ uses-permission >

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值