iOS调用webservice -- 【WJ】

注意:

本文主要介绍iOS如何调用webservice进行开发,以及我的需求中的UI控件使用;这里使用的数据格式是JSON,XML的话,N多年不用了,百度上随便查,好像都是关于XML的,我就不写了,反正也用不上。写的不尽如人意的地方,请见谅~

概述如下:

  • 环境 :XCode 7.2
  • 语言 :如果我没猜错的话,应该是Objective-C
  • 特点 :简单、直接、暴力,绝对让你有快感!!!

下面正式开始

一、Webservice接口 -- cus_order方法

cus_order
测试测试窗体只能用于来自本地计算机的请求。
SOAP 1.1以下是 SOAP 1.2 请求和响应示例。所显示的占位符需替换为实际值。

POST /testsdk/SDKService.asmx 
HTTP/1.1Host: ***.***.***.*** <!-- 主机地址 -->
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://microsoft.com/webservices/cus_order"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <cus_order xmlns="http://microsoft.com/webservices/">
      <cus_no>string</cus_no>            <!-- 参数 -->
      <order_date>string</order_date>    <!-- 参数 -->
    </cus_order >
  </soap:Body>
</soap:Envelope>

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
  <soap:Body>
    <cus_orderResponse xmlns="http://microsoft.com/webservices/">
      <cus_orderResult>string</cus_orderResult>
    </cus_orderResponse>
  </soap:Body>
</soap:Envelope>

SOAP 1.2
以下是 SOAP 1.2 请求和响应示例。所显示的占位符需替换为实际值。
POST /testsdk/SDKService.asmx HTTP/1.1
Host: ***.***.***.*** <!-- 主机地址 -->
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"> 
  <soap12:Body>
     <cus_order xmlns="http://microsoft.com/webservices/">
         <cus_no>string</cus_no>            <!-- 参数 -->
         <order_date>string</order_date>    <!-- 参数 -->
    </cus_order >
  </soap12:Body>
</soap12:Envelope>

HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
   <cus_orderResponse xmlns="http://microsoft.com/webservices/">
      <cus_orderResult>string</cus_orderResult>
   </cus_orderResponse >
</soap12:Body>
</soap12:Envelope>

简要说明

在本人提供的请求类中,调用webservice接口所需要如下:

ServiceURL 请求体 MethodName
服务器地址 <soap:Body>这里的内容</soap:Body> cus_order

上面所说的请求体是下面这种啦 --。--

<cus_order xmlns="http://microsoft.com/webservices/">
    <cus_no>string</cus_no>            <!-- 参数 -->
    <order_date>string</order_date>    <!-- 参数 -->
</cus_order >

好了,webservice接口就是这样;如果你还想了解Android调用webservice,记得收藏呀~


二、抽取出来的webservice请求类:

WJWebserviceHttpRequest.h

//
//  WJWebserviceHttpRequest.m
//  订单查询
//
//  Created by apple on 2017/2/22.
//  Copyright © 2017年 WangJun. All rights reserved.
//

#import <Foundation/Foundation.h>

/// 请求成功回调block
typedef void(^requestSuccessBlock)(id responseObject);
/// 请求失败回调block
typedef void(^requestFailureBlock)(NSError * error);

@interface WJWebserviceHttpRequest : NSObject

+(instancetype)shareHttpRequest;

-(void)httpRequestWithUrl:(NSString *)path andWithBodyStr:(NSString *)bodyStr andWithMethodNmae:(NSString *)requestMethodName andSuccessBlock:(requestSuccessBlock)success andFailureBlcok:(requestFailureBlock)failure;

@end

WJWebserviceHttpRequest.m

//
//  WJWebserviceHttpRequest.m
//  订单查询
//
//  Created by apple on 2017/2/22.
//  Copyright © 2017年 WangJun. All rights reserved.
//

#import "WJWebserviceHttpRequest.h"

@implementation WJWebserviceHttpRequest

static WJWebserviceHttpRequest * instance = nil;

+ (instancetype)shareHttpRequest
{
    
    static dispatch_once_t onceTocken;
    dispatch_once(&onceTocken, ^{
        instance = [[WJWebserviceHttpRequest alloc] init];
    });
    return instance;
}

-(void)webserviceHttpRequestWithUrl:(NSString *)path andWithBodyStr:(NSString *)bodyStr andWithMethodNmae:(NSString *)requestMethodName andSuccessBlock:(requestSuccessBlock)success andFailureBlcok:(requestFailureBlock)failure
{
    NSURL * pathUrl = [NSURL URLWithString:path];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:pathUrl];
    request.HTTPMethod = @"POST";
    
    NSString * soapMsg = [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body>%@</soap:Body></soap:Envelope>",bodyStr];
    NSData * soapMsgData = [soapMsg dataUsingEncoding:NSUTF8StringEncoding];
    
    // 命名空间
    NSString *nameSpace=@"http://microsoft.com/webservices/";
    // 方法名
    NSString *methodname=requestMethodName;
    
    NSString *msgLength = [NSString stringWithFormat:@"%ld", [soapMsg length]];
    NSString *soapAction=[NSString stringWithFormat:@"%@%@",nameSpace,methodname];
    NSDictionary *headField=[NSDictionary dictionaryWithObjectsAndKeys:[pathUrl host],@"Host",
                             @"text/xml; charset=utf-8",@"Content-Type",
                             msgLength,@"Content-Length",
                             soapAction,@"SOAPAction",nil];
    [request setAllHTTPHeaderFields:headField];
    request.HTTPBody = soapMsgData;
    
    NSURLSession * session = [NSURLSession sharedSession];
    NSURLSessionDataTask * dataTask =[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            failure(error);
        }
        else{
            success(data);
        }
    }];
    [dataTask resume];
}

@end
简要说明

方法中命名空间要对应你自己接口中的命名空间,具体怎么找你的命名空间就不重复了;


三、实现类

ViewController.m

//
//  ViewController.m
//  订单查询
//
//  Created by apple on 2017/2/22.
//  Copyright © 2017年 WangJun. All rights reserved.
//

#import "ViewController.h"
#import "WJWebserviceHttpRequest.h"
#import "Masonry.h"
#import "MJExtension.h"

@interface ViewController ()

@property (nonatomic, weak) UIButton *mButton;

@end

@implementation ViewController

- (void)viewDidLoad 
{
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor brownColor];
    
    UIButton *mButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [mButton setTitle:@"NB你就点我呀" forState:UIControlStateNormal];
    [mButton setTitle:@"算你NB" forState:UIControlStateHighlighted];
    [mButton setBackgroundColor:[UIColor redColor]];
    [mButton addTarget:self action:@selector(mButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:mButton];
    self.mButton = mButton;
    
    [self.mButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(200, 50));
        
    }];
}

/**
 *  获取webservice数据
 *
 *  @param btn 参数
 */
- (void)mButtonClick:(UIButton *)btn
{
    [self setUpCustOrder];           // 订单查询    
}

/**
 *  订单查询
 */
- (void)setUpCustOrder
{
    
    // 请求请求对象
    HJHttpRequest *hjRequest = [HJHttpRequest shareHttpRequest];
    // 设置请求路径
    NSString *serverUrl = @"http://***.***.***.***/testsdk/SDKService.asmx";
    // 设置请求体(这里获取参数是我写死的)
    NSString *bodyStr = @"<cus_order xmlns=\"http://microsoft.com/webservices/\"><cus_no>13</cus_no><order_date>2016-11-22</order_date></cus_order>";
    // 设置方法名
    NSString *methodName = @"cus_order";
    
    
    // 开始请求
    [hjRequest httpRequestWithUrl:serverUrl andWithBodyStr:bodyStr andWithMethodNmae:methodName andSuccessBlock:^(id responseObject) {
        NSLog(@"请求成功");
        NSString *jsonString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//        NSLog(@"看看里面的JSON\n%@",jsonString);

        // 字符串截取
        NSRange startRange = [jsonString rangeOfString:@"<cus_orderResult>"];
        NSRange endRagne = [jsonString rangeOfString:@"</cus_orderResult>"];
        NSRange reusltRagne = NSMakeRange(startRange.location + startRange.length, endRagne.location - startRange.location - startRange.length);
        NSString *resultString = [jsonString substringWithRange:reusltRagne];
//        NSLog(@"看看截取的内容\n%@",resultString);
        
        // 翻译一下,字符串转NSData
        NSString *requestTmp = [NSString stringWithString:resultString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];

        NSMutableDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
        NSMutableArray *dingdanArray = [DingDanBen mj_objectArrayWithKeyValuesArray:resultDic];
                for (DingDanBen *dingdan in dingdanArray) {
                    NSLog(@"name = %@",dingdan.prd_name);
                    NSLog(@"no = %@",dingdan.prd_no);
                    NSLog(@"yh = %@",dingdan.qty_yh);
                    NSLog(@"sh = %@",dingdan.qty_sh);
                    NSLog(@"sal_name = %@",dingdan.sal_name);
                    NSLog(@"sh_name = %@",dingdan.sh_name);
                    NSLog(@"ut = %@",dingdan.ut);
                }
        
    } andFailureBlcok:^(NSError *error) {
        NSLog(@"请求失败%@",error);
    }];
}

@end

简要说明

实现类中
Masonry.h,具体使用方式百度下载地址
MJExtension.h,具体使用方式百度下载地址

下面大家看下打印jsonString这个字符串

1.打印jsonString

2017-02-22 11:06:15.155 订单查询[5710:591254] 请求成功
2017-02-22 11:06:15.156 订单查询[5710:591254] 看看里面的JSON
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><cus_checkResponse xmlns="http://microsoft.com/webservices/"><cus_checkResult>[{"bz":"已提交","cus_up":"0.00","prd_name":"180克桂花叉烧肉(京味)","prd_no":"338","qty":"0.00","st":"已导入","user_name":"王峻","ut":"袋"}]</cus_checkResult></cus_checkResponse></soap:Body></soap:Envelope>

事实说明,这里其实是个NSString类型的,并不是服务器反给我们的JSON,因为前面还是带接口中的标签,如果要是直接使用里面的JSON格式数据,那么你就悲催了,什么都不会拿到的;所以,我们在这里需要用NSRange截取一下;

2.使用NSRange截取字符串

// 字符串截取
NSRange startRange = [jsonString rangeOfString:@"<cus_checkResult>"];
NSRange endRagne = [jsonString rangeOfString:@"</cus_checkResult>"];
NSRange reusltRagne = NSMakeRange(startRange.location + startRange.length, endRagne.location - startRange.location - startRange.length);
NSString *resultString = [jsonString substringWithRange:reusltRagne];

我们看一下打印的结果,截取后的字符串

2017-02-22 11:06:15.155 订单查询[5710:591254] 请求成功
2017-02-22 11:06:15.156 订单查询[5710:591254] 看看里面的JSON
[{"bz":"已提交","cus_up":"0.00","prd_name":"180克桂花叉烧肉(京味)","prd_no":"338","qty":"0.00","st":"已导入","user_name":"王峻","ut":"袋"}]

没错了,这个就是我们要的结果,但它仍然是个字符串

3.使用NSString转NSData

NSString *requestTmp = [NSString stringWithString:resultString];
NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];

大家看一下第2点的打印结果,JSON格式无疑,那么除去[ ]中括号是标准JSON格式的样例,包在数据外层的是{ }大括号,所以对应的就是字典!

OK了,下面接简单了,字典接数据,根据打印结果建立Model


四、实体类 -- Model

//
//  DingDanBen.h
//  订单查询
//
//  Created by WangJun on 17/2/4.
//  Copyright © 2017年 WangJun. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface DingDanBen : NSObject

@property (nonatomic, copy) NSString *prd_name;
@property (nonatomic, copy) NSString *prd_no;
@property (nonatomic, copy) NSString *qty_sh;
@property (nonatomic, copy) NSString *qty_yh;
@property (nonatomic, copy) NSString *sal_name;
@property (nonatomic, copy) NSString *sh_name;
@property (nonatomic, copy) NSString *ut;

@end

DingDanBen.m什么都不写。。


总结

希望大家喜欢我写的东西,转发收藏什么的,多多益善~
上面的所有代码都是复制粘贴我自己的,有些类名、变量名、参数名都是我后改的,有可能改错了,但是我相信,细心的你一定会发现。

最后,如果你有更好的,请回复我,并粘贴你的资料地址。
有事私信
WangJun 20170222

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,497评论 18 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,504评论 18 399
  • 生长在江南水乡,雨水充裕,然而,我不喜欢雨。 下雨天多麻烦啊,要带伞,伞又是易耗品,转头就落在了别人家。上学骑车,...
    盒子很随心阅读 693评论 1 11
  • 双十一来袭,商家的打折广告铺天盖地,商品信息也极显诱惑力,购物狂们不安分心开始躁动起来,购物车的各类物品琳琅满目。...
    幽兰小姐阅读 404评论 0 1
  • 1. 你是不是经常收到这类信息? “你也清清吧,不用回,不要让拉黑你的人占用你的空间”,有时候我一天能收到好几条这...
    沈善书阅读 2,376评论 8 27