[Android] 從ASP.NET Web Service取得資料
開發環境:Android 2.2 + KSOAP2
因為Android本身沒有可以直接處理的API,網路上不少人推薦的就是使用KSOAP2,使用的方式也蠻簡單的,不過如果你需要傳自訂物件,那就需要自行實作序列化的部份~Web Service的撰寫部份這邊就跳過不提,先來看一下簡單範例。
先宣告一個SoapObject,裡面是我們要回報給Server的東西,接回來的時候則依據需要利用SoapPrimitive或是SoapObject來處理。
//傳遞參數
request.addProperty("username", "google");
request.addProperty("password", "1234");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE("http://tempuri.org/webservice.asmx");
try
{
androidHttpTransport.call(SOAP_ACTION, envelope);
//若是單純的值,直接用SoapPrimitive接
SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
//SoapObject result = (SoapObject) envelope.getResponse();
boolean success = Boolean.parseBoolean(result.toString());
if (!success)
{
Log.e("map", "登入失敗!!");
}
}
catch (Exception e)
{
Log.e("map", e.toString());
}
可是今天如果參數是物件陣列或是自訂類別之類的要怎麼辦咧?那你就需要實作KvmSerializable了!假設我們今天需要處理的是建立一堆人員,傳入參數的SOAP格式是:
<User>
<Name></Name>
<Password></Password>
</User>
<User>
<Name></Name>
<Password></Password>
</User>
</list>
從這邊可以看到有二個類別,一個是list,一個是User,二個都需要各別實作KvmSerializable
{
public List<User> list = new ArrayList<User>();
public Object getProperty(int arg0)
{
return list.get(arg0);
}
public int getPropertyCount()
{
return list.size();
}
public void getPropertyInfo(int arg0, Hashtable arg1, PropertyInfo arg2)
{
arg2.type = User.class;
arg2.name = "User";
arg2.setValue(list.get(arg0));
}
public void setProperty(int arg0, Object arg1)
{
list.add(arg0, (User) arg1);
}
}
private class User implements KvmSerializable
{
public String Name;
public String Password;
public User(String name, String password)
{
this.Name = name;
this.Password = password;
}
public Object getProperty(int arg0)
{
switch (arg0)
{
case 0:
return Name;
case 1:
return Password;
}
}
public int getPropertyCount()
{
return 2;
}
public void getPropertyInfo(int arg0, Hashtable arg1, PropertyInfo arg2)
{
switch (arg0)
{
case 0:
arg2.name = "Name";
break;
case 1:
arg2.name = "Password";
break;
}
}
public void setProperty(int arg0, Object arg1)
{
switch (arg0)
{
case 0:
Name = String.valueOf(arg1);
break;
case 1:
Password = String.valueOf(arg1);
break;
}
}
}
參數帶入方式:
PropertyInfo propertyInfo = new PropertyInfo();
propertyInfo.setName("list");
propertyInfo.setValue(list);
request.addProperty(propertyInfo);
看起來還算蠻簡單的吧?不過我當初找寫法可是找超久的~~~~Orz