android Call WebService with complex types (Android调用复杂类型的WebService)

来源:互联网 发布:杭州淘宝服装有限公司 编辑:程序博客网 时间:2024/05/29 06:32

 

Calling web service on Android is possible with KSOAP2 (ksoap2-android-assembly-2.4-jar-with-dependencies.jar)  or you can write you own soap message formatter and can make http call using android apache http classes.

In this post i am going to explain calling web service using ksoap lib for dotnet service. This web service is hosted at http://bimbim.in/Sample/TestService.asmx. You can use this for your reference because Android emulator is not connecting with local web development server which comes with Visual Studio ( i don’t know exact reason).

 

For complete understanding i will suggest you to download complete android code from here 

Bimbimin.Android.Webservice.Client.rar (177.05 kb) and debug it using my web service URL.

 

First i will brief web service which i will use to explain web service calling.

I have created one serializable class Person with 4 attributes of different types in asp.net

 

[Serializable]public class Person{    private string _name = string.Empty;    private int _age = 0;    private float _salary = 100000.0f;    private DateTime? _dob = new DateTime(1980, 01, 15);     public float Salary    {        get { return _salary; }        set { _salary = value; }    }    public DateTime? Dob    {        get { return _dob; }        set { _dob = value; }    }     public int Age    {        get { return _age; }        set { _age = value; }    }    public string Name    {        get { return _name; }        set { _name = value; }    } }


 

and create two web method in web service GetSingle and SetValue.

 

One takes Person as input parameter and other return Person object.

 

Now i will explain how to call this web service method in Android using Ksoap 2. Although this lib has some bug and limitation but it is very useful.

In android application first we have to create a java class for Web service Person structure and we have to implement KvmSerializable interface in this class. KvmSerializable is used to transform soap message by ksoap library.

 

 

I have created four attributes in this class as web service class and Implemented KvmSerializable 4 methods.

  1. public int getPropertyCount(): return attribute count in our case it is 4.
  2. public void getPropertyInfo(int index, Hashtable arg1, PropertyInfo propertyInfo): Set propertyInfo attribute name and type, see above code listing.
  3. public Object getProperty(int index): Called by ksoap when formatting soap message.
  4. public void setProperty(int index, Object obj): Called by ksoap when created instance of classes from soap message response.

Note: Please used same sequence while writing these method as you have used in getPropertyInfo method.

Now make call using ksoap library

 

 

 

最后在Activity里调用   CallSetValue 和 CallGetSingle 方法就可以了。

原文地址:http://bimbim.in/post/2010/10/08/Android-Calling-Web-Service-with-complex-types.aspx