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;