注意:
本文主要介绍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