• iOS开发笔记 基于wsdl2objc调用asp.net WebService


    1.准备

    先下载待会要用到的工具 WSDL2ObjC-0.6.zip WSDL2ObjC-0.7-pre1.zip

    我用的是WSDL2ObjC-0.6.zip

    1.1搭建asp.net WebService项目并且部署在IIS服务器上面

    创建WebService服务项目后先在Web.config添加节点,设置WebService远程调试访问,否则会出现:

    “测试窗体只能用于来自本地计算机的请求”

     

    <webServices>
    <protocols>
    <add name="HttpSoap" />
    <add name="HttpPost" />
    <add name="HttpGet" />
    <add name="Documentation" />
    </protocols>
    </webServices>
    View Code

    创建类库添加Model实体类

    public class CourseEntity
    {
    
        private int courseID;
    
        public int CourseID
        {
            get { return courseID; }
            set { courseID = value; }
        }
        private int parentID;
    
        public int ParentID
        {
            get { return parentID; }
            set { parentID = value; }
        }
        private string courseName;
    
        public string CourseName
        {
            get { return courseName; }
            set { courseName = value; }
        }
        private string coursePPT;
    
        public string CoursePPT
        {
            get { return coursePPT; }
            set { coursePPT = value; }
        }
        private string courseVidio;
    
        public string CourseVidio
        {
            get { return courseVidio; }
            set { courseVidio = value; }
        }
        
    }
    View Code

    事先做好Model实体类的生成dll文件,直接添加引用至bin目录下

    在项目当中添加一个数据库操作类DBOperation.cs

    接下来我们打开Service.cs文件。

    2.asp.net WebService返回Xml Json格式数据

    2.1返回Xml格式数据

    service.cs代码如下:

      [WebMethod(Description = "ProblemPaper")]
        public List<ProblemPaperEntity> ProblemPaper(String prkid)
        {
            return dbOperation.ProblemPaper(prkid);
        }
    View Code

    DBOperation.cs代码如下:

    /// <summary>
        /// 题库试卷目录表 ProblemPaper
        /// </summary>
        /// <returns>PPID(编号)PRKID(上一级)PTID(类型编号)Name(名称)ProblemNum(目录数量))</returns>
        public List<ProblemPaperEntity> ProblemPaper(String prkid)
        {
    
    
            List<ProblemPaperEntity> list = new List<ProblemPaperEntity>();
    
            ProblemPaperEntity model = null;
    
    
    
            try
            {
                string sql = "select PPID,PRKID,PTID,Name,ProblemNum,Row_Number() over(order by PPID ) as row_number from ProblemPaper where 1=1";
                sql += "  and prkid in ( select * from getProblemResourseByID("+prkid+"))";
                string s = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                SqlConnection con = new SqlConnection(s);
                con.Open();
                SqlCommand cmd = new SqlCommand(sql, con);
                SqlDataReader reader = cmd.ExecuteReader();
    
    
                while (reader.Read())
                {
                    model = new ProblemPaperEntity();
    
                    model.PPID = reader.GetInt32(0);
                    model.PRKID = reader.GetInt32(1);
                    model.PTID = reader.GetInt32(2);
                    model.Name = reader.GetString(3);
                    model.ProblemNum = reader.GetInt32(4);
                  
                    list.Add(model);
                }
    
    
    
                reader.Close();
                cmd.Dispose();
    
            }
            catch (Exception)
            {
    
            }
    
    
            return list;
    
        }
    View Code

    从service.cs代码中可以看到ProblemPaper方法前面 [WebMethod]指示web服务提供的方法

    public方法能否被调用者访问取决于这个方法是否是一个“WebMethod”,在编写方法的时候注意

    方法前面是否含有WebMethod

    2.2返回Json格式数据

    service.cs 代码如下:

    [WebMethod(Description = "JsonProblemPaper2")]
          [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
          public string JsonProblemPaper2(String prkid)
          {
              return new JavaScriptSerializer().Serialize(dbOperation.ProblemPaper(prkid));
          }
    View Code

    DBOperation.cs代码如下:

    public List<string> JsonProblemPaper(String prkid)
        {
    
    
            List<String> list = new List<String>();
    
           
    
    
    
            try
            {
                string sql = "select PPID,PRKID,PTID,Name,ProblemNum,Row_Number() over(order by PPID ) as row_number from ProblemPaper where 1=1";
                sql += "  and prkid in ( select * from getProblemResourseByID(" + prkid + "))";
                string s = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                SqlConnection con = new SqlConnection(s);
                con.Open();
                SqlCommand cmd = new SqlCommand(sql, con);
                SqlDataReader reader = cmd.ExecuteReader();
    
    
                while (reader.Read())
                {
    
    
                    list.Add(reader[0].ToString());
                    list.Add(reader[1].ToString());
                    list.Add(reader[2].ToString()) ;
                    list.Add(reader[3].ToString());
                    list.Add(reader[4].ToString());
    
                  
                }
    
    
    
                reader.Close();
                cmd.Dispose();
    
            }
            catch (Exception)
            {
    
            }
    
    
            return list;
    
        }
    View Code

    返回Json格式,需要在方法前面同时声明

    [WebMethod(Description = "××××")]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

    返回格式: return new JavaScriptSerializer().Serialize(dbOperation.ProblemPaper(prkid));

    接下来的方法编写由自己扩展,编写完WebService

     3.部署

    环境windows Server2008 IIS 7.5  SqlServer2012

    选择应用程序池.Net v.2.0,切记,如在部署遇到问题可以查阅其他相关资料,在这里

    就不多详细

     4.IOS基于wsdl2objc调用asp.net WebService

    4.1使用wsdl2objc工具

     在官网上下载有2个版本,我用的是WSDL2ObjC-0.6.zip,

    部署完毕后,打开wsdl2objc

    Parse WSDL后稍等15秒左右出现Finish!查看导入目录

    将生成的所有文件放置在wsdl2objc文件夹

    尝试编译出现错误如下:

    解决方法:这里有2个错误

    1."libxml/tree.h" file not found

    2.ARC开启与禁止

    第一个错误解决方法如下:

    支持libxml2

    TARGETS -> Build Settings -> Linking -> Other Linker Flags,设置“-lxml2”

    TARGETS -> Build Settings -> Search Paths-> Header Search Paths,设置“/usr/include/libxml2”

     

    TARGETS -> Build Settings -> Apple LLVM5.0-Language-Objective C> Objective-C Automatic Reference Counting,设置“No”

     第二个错误解决方法:

    TARGETS -> Build Settings ->All 搜索"compiler"

    Apple LLVM 5.0- Custom CompilerFlags OtherWaning Flags 设置"-Wall"

    打开Xcode的自动转换工具

    错误解决后,项目就可以完整的运行了,在第一个错误当中我花的时间有些多,

    如果你在做的过程当中遇到这个错误

    请重新尝试再做看上面二个错误的解决方法,在第二个错误记得一次性转换ARC

    在项目当中还会用到手动设置ARC

    手动ARC设置方法如下:

    1.在Compiler Flags一列加上-fno-objc-arc就表示禁止这个.m文件的ARC

    2.在Compiler Flags一列加上-fobjc-arc就表示开启这个.m文件的ARC

    参考资料:http://blog.csdn.net/a283127993/article/details/11082179

                http://blog.csdn.net/q199109106q/article/details/8565403

    5. IOS客户端解析xml,json数据

    接下来详细说明如何解析xml,json,往往遇到问题我就花了就是整整一天时间来做

    5.1 IOS客户端解析xml无参数据

    代码如下:

    -(void)getXml{
      NSMutableArray *result;
    ServiceSoap12Bingding *binding =[Service ServiceSoap];
    Service_Course *request = [[Service_Course alloc] init];
    
    ServiceSoap12BindingResponse *response = [binding CourseUsingParameters:request];
    for(id mine in response.bodyParts){
        if([mine isKindOfClass:[Service_CourseResponse class]])
    {
        [request  release];
        result = [mine CourseResult].CourseEntity;
    
    }
    for(Service_CourseEntity *t in result){
    
        NSLog(@"ID:%d ParentID:%d CourseName:%@ CoursePPT:%@ CourseVidio:%@",[t.CourseID intvalue],
    [t.ParentID intvalue],t.CourseName,t.CoursePPT,t.CourseVidio
    );
    }
    
    
    
    }         
    
    
    }
    View Code

    5.2 IOS客户端解析xml有参数数据

    -(void)getXml2{
      NSMutableArray *result;
    ServiceSoap12Bingding *binding =[Service ServiceSoap];
    Service_ProblemPaper *request = [[Service_ProblemPaper alloc] init];
    request.prkid=@"1";
    
    ServiceSoap12BindingResponse *response = [binding ProblemPaperUsingParameters:request];
    for(id mine in response.bodyParts){
        if([mine isKindOfClass:[Service_ProblemPaperResponse class]])
    {
        [request  release];
        result = [mine ProblemPaperResult].ProblemPaperEntity;
    
    }
    for(Service_CourseEntity *t in result){
    
        NSLog(@"PPID:%d],
    [t.PPID intvalue]);
    }
    
    
    
    }  
    View Code

    代码如下:

    5.3 IOS客户端解析json有参数据

    代码如下:

    -(void)getJson{
      NSMutableArray *result;
     NSData*data;
    ServiceSoap12Bingding *binding =[Service ServiceSoap];
    Service_JsonProblemPaper2 *request = [[Service_JsonProblemPaper2 alloc] init];
    request.prkid=@"1";
    
    ServiceSoap12BindingResponse *response = [binding JsonProblemPaper2UsingParameters:request];
    for(id mine in response.bodyParts){
        if([mine isKindOfClass:[Service_JsonProblemPaper2Response class]])
    {
        [request  release];
        result = [mine JsonProblemPaper2Result] ;
        data= [result dataUsingEncoding:NSUTF8StringEncoding];
    
        NSLog(@"data:%@",data);  
       NSDictionary *dict =[NSjSONSerialization JSONbjectWithData:data  options:NSJSONReadingAllowFragmentS error:nil];
    if(dict == nil)
    {
      return ;
    }
    else{
         for(NSString *ds in dict)
         {
            NSLog(@"json%@",[ds objectForKey:@"Name"]);
        }
    }
    }
    
    
    
    
    } 
    View Code

    在这里我只对解析json有参数据说明,在这里我遇到不少问题,花的时间挺多的,

    IOS客户端解析xml有参数数据,IOS客户端解析xml有参数数据

    参考代码就可以实现,在解析json有参数据,遇到了几个问题,

    就几行代码也花了好久,断断续续抽出时间做,最后才完成,下面是如何将NSString

    最后完整的放入NSDictionary,并且取出相应的键值,result是返回类型的数据

    将NSString转化为NSData

    [result dataUsingEncoding:NSUTF8StringEncoding];

    将result类型的数据,转成UTF8的数据

    首先我们将result类型的数据,转成UTF8的数据

    将JSON串转化为字典

    苹果引入了一个解析JSON串的NSJSONSerialization类。
    通过该类,我们可以完成JSON数据与NSDictionary和NSArray之间的转化

    开始的时候想将返回的NSString数据转化为NSDictionary即NSString-NSDictionary返回的数据为null

    所以采用NSString-NSData-NSDictionary最后成功解决数据为null问题,数据成功拿到Name属性值和其他属性值

    在这里我只打印Name属性值

    6.总结

      该博文面向初学者,大牛请不要喷。写到这里,又复习了好多知识,遇到之前没发现的错误,但是耐心下来,问题总会解决,

     WebService和客户端源码有需要的话可以留下邮箱,既然来了,对你有帮助,推荐支持一下呗!

    http://www.cnblogs.com/linmingjun/p/4382565.html 作者

  • 相关阅读:
    arthas Java诊断工具
    tomcat结构 请求处理过程 和 常见参数
    Dubbo 测试用例 获取注册中心的其他服务
    Vue3 父子组件传值,defineProps,defineEmits,以及父组件调用子组件的方法 defineExpose
    Snowflake
    js中Array和Object的keys(),values()和entries()方法
    深度拷贝
    deepin系统解决增删改文件没有变化
    文献的类别与引用方式
    读万卷书不如行万里路
  • 原文地址:https://www.cnblogs.com/linmingjun/p/4382565.html
Copyright © 2020-2023  润新知