Android调用基于.net的WebService

在实际开发项目中,有时候会为Android开发团队提供一些接口,一般是以asmx文件的方式来承载。而公布出去的数据一般上都是标准的json数据。但是在实际过程中,发现Android团队那边并不是通过将JSON序列化成类对象来进行解析的(通过parse json数据来进行),所以我这里要提供以下我自己在实际项目中,使用的方法,以期起到抛砖引玉的作用。

我们先在.net端建立两个WebService对象:

首先,建立一个名称为GetPhoneUnCharged的对象,用来获取暂未充值完成的手机列表用户。

 1:    #region 总体说明:获取未发送的手机充值列表
 2:          [WebMethod(Description = "总体说明:获取未发送的手机充值列表")]
 3:          public string GetPhoneUnCharged()
 4:          {
 5:              using (var e = new brnmallEntities())
 6:              {
 7:                  var result = from p in e.cha_phonecharge where p.chargestateid == 1 select p;
 8:                  return JsonConvert.SerializeObject(result.ToList());
 9:              }
10:          }
11:          #endregion
12:  

从上面代码可以看出,我们返回的是被Newtonsoft.json组件序列化的json字符串数组。

我们从捕获的截图中,可以看到我们返回的JSON字符串数据:

技术分享

然后,在.net中,我们创建如下的DTO对象:

 1:  public class cha_phonechargedto
 2:  {
 3:         public int phonechargeid { get; set; }
 4:         public int uid { get; set; }
 5:         public string chargephone { get; set; }
 6:         public DateTime? chargetime { get; set; }
 7:         public int chargestateid { get; set; }
 8:         public string chargestate { get; set; }
 9:         public decimal chagemoney { get; set; }
10:         public string chargememo { get; set; }
11:         public int chargetypeid { get; set; }
12:         public int serviceid { get; set; }
13:   
14:         public string username { get; set; } //用户名称
15:         public string chargetype { get; set; } //支付,还是缴费
16:         public string servicename { get; set; } //运营商名称
17:  
18:         public bool error { get; set; }
19:         public string message { get; set; }
20:     }
21:   

这个DTO对象主要就是返回一些用户数据以供Android客户端调用。

下面我们来添加我们的WebService方法:

 1:   #region 总体说明:手工缴费(兼容性放法)
 2:          [WebMethod(Description = "总体说明:手工缴费(兼容性放法)", MessageName = "ManualCharge")]
 3:          public string ManualCharge(string phonechargeid)
 4:          {
 5:              int phonechargeidInInt32;
 6:              if (string.IsNullOrEmpty(phonechargeid))
 7:                  return JsonConvert.SerializeObject(new cha_phonechargedto() { error = true, message = "缴费序号不能为空!" });
 8:              if (!Int32.TryParse(phonechargeid, out phonechargeidInInt32))
 9:                  return JsonConvert.SerializeObject(new cha_phonechargedto() { error = true, message = "缴费序号只能为数字型!" });
10:   
11:              using (var e = new brnmallEntities())
12:              {
13:                  var result = (from p in e.cha_phonecharge where p.phonechargeid == phonechargeidInInt32 select p).FirstOrDefault();
14:                  if (result == null)
15:                      return JsonConvert.SerializeObject(new cha_phonechargedto() { error = true, message = "未找到缴费记录!" });
16:                  else
17:                  {
18:                      //如果处于可以缴费的模式
19:                      if (result.chargestateid == 1)
20:                      {
21:                          result.chargestateid = 2; //缴费成功
22:                          result.chargememo = "于[" + DateTime.Now.ToString("yyyy年MM月dd日 hh:mm:ss") + "]自动缴费成功";
23:                          try
24:                          {
25:                              e.SaveChanges();
26:                              return JsonConvert.SerializeObject(new cha_phonechargedto() { error = false, message = "手工缴费成功!" });
27:                          }
28:                          catch (Exception ex)
29:                          {
30:                              return JsonConvert.SerializeObject(new cha_phonechargedto() { error = true, message = ex.Message });
31:                          }
32:                      }
33:                      else if (result.chargestateid == 2) //如果已经缴费,则无需重复缴费
34:                      {
35:                          result.chargememo = "于[" + DateTime.Now.ToString("yyyy年MM月dd日 hh:mm:ss") + "]有重复缴费行为,已被自动处理";
36:                      }
37:                      else  //其他未知原因,导致的不能缴费的情况
38:                      {
39:                          result.chargememo = "于[" + DateTime.Now.ToString("yyyy年MM月dd日 hh:mm:ss") + "]发现本记录异常,无法被自动缴费";
40:                      }
41:                  }
42:                  return JsonConvert.SerializeObject(new cha_phonechargedto() { error = true, message = "手工缴费成功!" });
43:              }
44:          }
45:          #endregion
46:  

这个方法最后返回的数据为String类型的标准的JSON数据。在返回值中,我已经利用Newtonsoft.json组件将对象转换成了标准的json数据。

以上就是.net WebService所有的内容了。我们再来看看Android端怎么进行的。

首先,我们需要下载两个用于json数据解析的jar包:gson-2.2.4.jarksoap2-android-assembly-2.4-jar-with-dependencies.jar,将其添加到libs目录下。

其次,我们需要在Android端,创建一个一模一样的DTO对象:cha_phonechargedto。

然后,开始编写解析代码如下:

  1:  public void run() {
  2:              System.out.println("Polling...");
  3:   
  4:              String nameSpace = "http://tempuri.org/";
  5:              String serviceURL = "http://116.255.218.25:8001/ChargeService.asmx";
  6:   
  7:              String methodName = "GetPhoneUnCharged";
  8:              String soapAction = "http://tempuri.org/GetPhoneUnCharged";
  9:              SoapObject request = new SoapObject(nameSpace, methodName);
 10:   
 11:              SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
 12:                      SoapEnvelope.VER11);
 13:              envelope.bodyOut = request;
 14:              envelope.dotNet = true;
 15:              HttpTransportSE ht = new HttpTransportSE(serviceURL);
 16:              ht.debug = false;
 17:              try {
 18:                  ht.call(soapAction, envelope);
 19:                  if (envelope.getResponse() != null) {
 20:                      String result = envelope.getResponse().toString();
 21:                      Log.d("result", result);
 22:   
 23:                      Gson gson = new Gson();
 24:                      List<cha_phonechargedto> ps = gson.fromJson(result,new TypeToken<List<cha_phonechargedto>>() {}.getType());
 25:   
 26:                      for (int i = 0; i < ps.size(); i++) {
 27:                          cha_phonechargedto p = ps.get(i);
 28:   
 29:                          String phone = p.getChargephone().toString(); // 电话号码
 30:                          String fee = p.getChagemoney().toString(); // 缴费金额
 31:                          String stuffID = p.getServiceid().toString(); // ServiceCompany  1:电信  2:移动 3:联通
 32:                          String phonechargeid = p.getPhonechargeid().toString();
 33:                          int feeEx= new Double(fee).intValue();
 34:   
 35:                          System.out.println(phone + "|" + fee + "|" + stuffID+ "|" + phonechargeid);
 36:   
 37:                          String messageDaemon = "";
 38:                          String messageTo = "";
 39:                          String smsCenterPhone = "";
 40:   
117:                          if (stuffID.equalsIgnoreCase("3")) // 联通 Send To 10011
118:                          {
119:                              messageDaemon = "CZ#568614#" + phone + "#" + feeEx;
120:                              messageTo = "10011";
121:                              smsCenterPhone = "13010761500";
122:                              Log.d("result", messageDaemon + "|" + messageTo + "|"+ smsCenterPhone);
123:   
124:                              String methodName1 = "ManualCharge";
125:                              String soapAction1 = "http://tempuri.org/ManualCharge";
126:                              SoapObject request1 = new SoapObject(nameSpace,methodName1);
127:                              // 如果有参数,可以加入,没有的话,则忽略
128:                              Log.d("phonechargeid", phonechargeid);
129:                              request1.addProperty("phonechargeid", phonechargeid);
130:   
131:                              SoapSerializationEnvelope envelope1 = new SoapSerializationEnvelope(SoapEnvelope.VER11);
132:                              envelope1.bodyOut = request1;
133:                              envelope1.dotNet = true;
134:   
135:                              ht.call(soapAction1, envelope1);
136:                              if (envelope1.getResponse() != null) {
137:                                  String operation = envelope1.getResponse().toString();
138:                                  Log.d("operation", operation);
139:   
140:                                  Gson gsonResponse = new Gson();
141:                                  cha_phonechargedto resultResponse = gsonResponse.fromJson(operation,new TypeToken<cha_phonechargedto>() {}.getType());
142:   
143:                                  boolean errorflag = resultResponse.getError();
144:   
145:                                  if(!errorflag) //can send message out 
146:                                   {
147:                                      // Send Message Out
148:                                      SmsManager smsManager = SmsManager.getDefault();
149:                                      smsManager.sendTextMessage(messageTo,smsCenterPhone, messageDaemon, null, null);
150:   
151:                                      Log.d("result", messageDaemon + " have sent");
152:                                  }
153:                              }
154:                          }
155:   
156:                          Thread.sleep(2000);
157:                      }
158:                  }
159:              } catch (Exception e) {
160:                  e.printStackTrace();
161:   
162:              }
163:          }
164:      }

首先,建立SoapObject来承载要Invoke的函数名称,然后通过Gson的fromJson方法,将WebService提供的JSON数据,序列化到List<cha_phonechargedto>对象中去。最后就是通过一系列的逻辑,来实现软件需要实现的目的。

其实说起来挺简单的。

但是也许有人会问,如果我不知道你们提供的cha_phonechargedto对象里面的内容,咋办呢? 其实很简单,网上已经有专门提供JSON数据类生成的服务了,我们可以拿好我们的json数据,直接去生成类去。

我们的json数据如下:

[
{
"$id": "1",
"phonechargeid": 1626,
"uid": 9,
"chargephone": "18239236557",
"chargetime": "2015-02-02T18:05:39.8",
"chargestateid": 1,
"chagemoney": 50,
"chargememo": "网页端手机充值",
"chargetypeid": 2,
"serviceid": 2,
"EntityKey": {
"$id": "2",
"EntitySetName": "cha_phonecharge",
"EntityContainerName": "brnmallEntities",
"EntityKeyValues": [
{
"Key": "phonechargeid",
"Type": "System.Int32",
"Value": "1626"
}
]
}
},
{
"$id": "3",
"phonechargeid": 1634,
"uid": 9,
"chargephone": "18239236557",
"chargetime": "2015-02-03T10:11:57.143",
"chargestateid": 1,
"chagemoney": 50,
"chargememo": "网页端手机充值",
"chargetypeid": 2,
"serviceid": 2,
"EntityKey": {
"$id": "4",
"EntitySetName": "cha_phonecharge",
"EntityContainerName": "brnmallEntities",
"EntityKeyValues": [
{
"Key": "phonechargeid",
"Type": "System.Int32",
"Value": "1634"
}
]
}
}
]

然后将上面数据拷贝到http://tools.wx6.org/json2csharp/这个网站中,点击生成按钮,可以生成如下的类对象:

 1:   
 2:   
 3:  public class EntityKeyValues
 4:  {
 5:      public string Key { get; set; }
 6:      public string Type { get; set; }
 7:      public int Value { get; set; }
 8:  }
 9:  public class EntityKey
10:  {
11:      public string EntitySetName { get; set; }
12:      public string EntityContainerName { get; set; }
13:      public List<EntityKeyValues> EntityKeyValues { get; set; }
14:  }
15:  public class Root
16:  {
17:      public int Phonechargeid { get; set; }
18:      public int Uid { get; set; }
19:      public long Chargephone { get; set; }
20:      public DateTime Chargetime { get; set; }
21:      public int Chargestateid { get; set; }
22:      public int Chagemoney { get; set; }
23:      public string Chargememo { get; set; }
24:      public int Chargetypeid { get; set; }
25:      public int Serviceid { get; set; }
26:      public EntityKey EntityKey { get; set; }
27:  }
28:   

看看,是不是很相似呢? 相信你把这些对象直接转变为java中的dto对象,该是很简单的了。

上面有多余字段,你可以不加某些属性,就可以过滤掉不想要的字段。

期望对你有用,谢谢。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。