在实际开发项目中,有时候会为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.jar 和 ksoap2-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://******: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 = "××××××" + phone + "#" + feeEx;
120:                              messageTo = "10011";
121:                              smsCenterPhone = "13000000000";
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"
}
]
}
}
]

[
{
"$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对象,该是很简单的了。

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

期望对你有用,谢谢。

Android调用基于.net的WebService的更多相关文章

  1. python发布及调用基于SOAP的webservice

    现如今面向服务(SOA)的架构设计已经成为主流,把公用的服务打包成一个个webservice供各方调用是一种非常常用的做法,而应用最广泛的则是基于SOAP协议和wsdl的webservice.本文讲解 ...

  2. 在Android中调用C#写的WebService(附源代码)

    由于项目中要使用Android调用C#写的WebService,于是便有了这篇文章.在学习的过程中,发现在C#中直接调用WebService方便得多,直接添加一个引用,便可以直接使用将WebServi ...

  3. Android调用C#的WebService

    Android调用C#写的WebService 学习自: http://www.cnblogs.com/kissazi2/p/3406662.html 运行环境 Win10 VS 2015 Andro ...

  4. Android调用WebService(转)

    Android调用WebService WebService是一种基于SOAP协议的远程调用标准,通过 webservice可以将不同操作系统平台.不同语言.不同技术整合到一块.在Android SD ...

  5. Android调用天气预报的WebService简单例子

    下面例子改自网上例子:http://express.ruanko.com/ruanko-express_34/technologyexchange5.html 不过网上这个例子有些没有说明,有些情况不 ...

  6. Android使用ksoap2调用C#中的webservice实现图像上传

    目录: 一. android使用ksoap2调用webservice 二. 异步调用 三. Android使用ksoap2调用C#中的webservice实现图像上传参考方法 四. 图像传输中Base ...

  7. android调用webservice接口获取信息

    我的有一篇博客上讲了如何基于CXF搭建webservice,service层的接口会被部署到tomcat上,这一篇我就讲一下如何在安卓中调用这些接口传递参数. 1.在lib中放入ksoap2的jar包 ...

  8. Android调用.net的webservice服务器接收参数为空的情况

    问题描述:安卓开发中,用Android调用.net开发的wenService时候,从Android客户端传递参数到服务器端,服务器端接收为空 解决方法: 1.设置envelope.dotNet = t ...

  9. Android客户端调用Asp.net的WebService

    Android客户端调用Asp.net的WebService 我来说两句 |2011-11-23 13:39:15 在Android端为了与服务器端进行通信有几种方法:1.Socket通信2.WCF通 ...

随机推荐

  1. 设计模式-01-MVC

    概述 Model-View-Controller(MVC),即模型-视图-控制器. MVC将软件系统分成三大部分:Model,View,Controller,三个部分通过某种机制通信 M.V.C的职能 ...

  2. 为Asp.net MVC中的RenderSection设置默认内容

    1. RenderSection的简单介绍 Asp.net MVC中提供了RenderSection方法,这样就能够在Layout中定义一些区块,这些区块留给使用Layout的view来实现比如我们定 ...

  3. Effective Java 13 Minimize the accessibility of classes and members

    Information hiding is important for many reasons, most of which stem from the fact that it decouples ...

  4. PHP模拟发送POST请求之三、用Telnet和fsockopen()模拟发送POST信息

    了解完了HTTP头信息和URL信息的具体内容,我们开始尝试自己动手写一段头信息发送到服务器.Windows内置命令Telnet可以帮助我们发送简单的HTTP请求. 并且TELNET是一个特别灵活的工具 ...

  5. python代码学习day03-序列化学习pickle及json

    #!/usr/bin/env python #coding:utf8 import pickle,json import datetime dic1 = {'name':'alex', 'age':4 ...

  6. Spring 通过XML配置文件以及通过注解形式来AOP 来实现前置,环绕,异常通知,返回后通知,后通知

    本节主要内容: 一.Spring 通过XML配置文件形式来AOP 来实现前置,环绕,异常通知     1. Spring AOP  前置通知 XML配置使用案例     2. Spring AOP   ...

  7. (转载)web测试方法总结

    web测试方法总结 一.输入框 1.字符型输入框: (1)字符型输入框:英文全角.英文半角.数字.空或者空格.特殊字符“~!@#¥%……&*?[]{}”特别要注意单引号和&符号.禁止直 ...

  8. CListCtrl

    CListCtrl CCmdTarget     └CListCtrl CListCtrl类封装"列表视图控件"功能,显示每个包含图标(列表视图中)和标签的收集.除图标和标签外,每 ...

  9. Linux系统之用户、群组和权限

    一.用户管理 创建用户时,系统为用户分配一个唯一的编号UID,同时为用户创建一个同名的组,并为组分配一个编号GID,并把该用户加入该组中. 系统规定: uid: 0       特权用户      u ...

  10. The available repos for opensuse13.2

    opensuse13.2国内源和设置命令   ustc-osshttp://mirrors.ustc.edu.cn/opensuse/distribution/13.2/repo/oss/ustc-n ...