Android 傳遞復雜對象到wcf方法:
wcf 服務端相關配置:
1 創建一個User
[DataContract]
public class User
{
[DataMember]
public int Age
{
get;
set;
}
[DataMember]
public String Name
{
get;
set;
}
}
2 創建一個方法
#region IService1 成員
public string GetUserInfo(User user)
{
if (null != user)
return user.Age + " " + user.Name;
return "";
}
#endregion
3 配置先關參數,需要注意的是 bingding采用
<services>
<service name="test.Service1">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration=""
contract="test.IService1">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8732/Design_Time_Addresses/test/Service1/" />
</baseAddresses>
</host>
</service>
</services>
android端配置:
1 創建一個相同的對象在Android端
public class User{
public static Class UserClass = User.class;
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public static User fromString(String s)
{
User result = new User();
String[] tokens = s.split("=");
String age = tokens[1].split(";")[0];
String name = tokens[2].split(";")[0];
result.Age = Integer.parseInt(age);
result.Name = name;
return result;
}
private int Age;
private String Name;
}
2 創建一個User對象的Marshal對象
public class MarshalUser implements Marshal {
private static String dataContract = "http://schemas.datacontract.org/2004/07/test";//要注意這兒的定義,具體查看wcf端的xml是如何定義的
@Override
public Object readInstance(XmlPullParser parser, String arg1, String arg2,
PropertyInfo arg3) throws IOException, XmlPullParserException {
return User.fromString(parser.nextText());
}
@Override
public void register(SoapSerializationEnvelope cm) {
cm.addMapping(dataContract, "user", User.class, this);
}
@Override
public void writeInstance(XmlSerializer writer, Object obj)
throws IOException {
User user = (User)obj;
writer.startTag(dataContract, "Age");
writer.text(Integer.toString(user.getAge()));
writer.endTag(dataContract, "Age");
writer.startTag(dataContract, "Name");
writer.text(user.getName());
writer.endTag(dataContract, "Name");
}
}
3 調用wcf,並定義complex type的內容如下:
SoapObject request = new SoapObject(serviceNameSpace, methodName);
User user = new User();
user.setAge(10);
user.setName("corning");
PropertyInfo pi = new PropertyInfo();
pi.setName("user");
pi.setValue(user);
pi.setType(user.getClass());
request.addProperty(pi);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.bodyOut = request;
envelope.implicitTypes = true;
envelope.addMapping(serviceNameSpace, User.UserClass.getSimpleName(), User.UserClass);
MarshalUser userMarshal = new MarshalUser();
userMarshal.register(envelope);
// Android傳輸對象
HttpTransportSE transport = new HttpTransportSE(serviceURL);
transport.debug = true;