注意:
本文主要介紹iOS如何調(diào)用webservice進(jìn)行開發(fā)罐寨,以及我的需求中的UI控件使用;這里使用的數(shù)據(jù)格式是JSON序矩,XML的話鸯绿,N多年不用了,百度上隨便查贮泞,好像都是關(guān)于XML的楞慈,我就不寫了,反正也用不上啃擦。寫的不盡如人意的地方囊蓝,請見諒~
概述如下:
- 環(huán)境 :XCode 7.2
- 語言 :如果我沒猜錯的話,應(yīng)該是Objective-C
- 特點 :簡單令蛉、直接聚霜、暴力狡恬,絕對讓你有快感!P睢弟劲!
下面正式開始
一、Webservice接口 -- cus_order方法
cus_order
測試測試窗體只能用于來自本地計算機(jī)的請求姥芥。
SOAP 1.1以下是 SOAP 1.2 請求和響應(yīng)示例兔乞。所顯示的占位符需替換為實際值。
POST /testsdk/SDKService.asmx
HTTP/1.1Host: ***.***.***.*** <!-- 主機(jī)地址 -->
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> <!-- 參數(shù) -->
<order_date>string</order_date> <!-- 參數(shù) -->
</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 請求和響應(yīng)示例凉唐。所顯示的占位符需替換為實際值庸追。
POST /testsdk/SDKService.asmx HTTP/1.1
Host: ***.***.***.*** <!-- 主機(jī)地址 -->
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> <!-- 參數(shù) -->
<order_date>string</order_date> <!-- 參數(shù) -->
</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>
簡要說明
在本人提供的請求類中,調(diào)用webservice接口所需要如下:
ServiceURL | 請求體 | MethodName |
---|---|---|
服務(wù)器地址 | <soap:Body>這里的內(nèi)容</soap:Body> | cus_order |
上面所說的請求體是下面這種啦 --台囱。--
<cus_order xmlns="http://microsoft.com/webservices/">
<cus_no>string</cus_no> <!-- 參數(shù) -->
<order_date>string</order_date> <!-- 參數(shù) -->
</cus_order >
好了淡溯,webservice接口就是這樣;如果你還想了解Android調(diào)用webservice簿训,記得收藏呀~
二咱娶、抽取出來的webservice請求類:
WJWebserviceHttpRequest.h
//
// WJWebserviceHttpRequest.m
// 訂單查詢
//
// Created by apple on 2017/2/22.
// Copyright ? 2017年 WangJun. All rights reserved.
//
#import <Foundation/Foundation.h>
/// 請求成功回調(diào)block
typedef void(^requestSuccessBlock)(id responseObject);
/// 請求失敗回調(diào)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
簡要說明
方法中命名空間要對應(yīng)你自己接口中的命名空間,具體怎么找你的命名空間就不重復(fù)了强品;
三膘侮、實現(xiàn)類
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數(shù)據(jù)
*
* @param btn 參數(shù)
*/
- (void)mButtonClick:(UIButton *)btn
{
[self setUpCustOrder]; // 訂單查詢
}
/**
* 訂單查詢
*/
- (void)setUpCustOrder
{
// 請求請求對象
HJHttpRequest *hjRequest = [HJHttpRequest shareHttpRequest];
// 設(shè)置請求路徑
NSString *serverUrl = @"http://***.***.***.***/testsdk/SDKService.asmx";
// 設(shè)置請求體(這里獲取參數(shù)是我寫死的)
NSString *bodyStr = @"<cus_order xmlns=\"http://microsoft.com/webservices/\"><cus_no>13</cus_no><order_date>2016-11-22</order_date></cus_order>";
// 設(shè)置方法名
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èi)容\n%@",resultString);
// 翻譯一下,字符串轉(zhuǎn)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
簡要說明
實現(xiàn)類中
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":"已導(dǎo)入","user_name":"王峻","ut":"袋"}]</cus_checkResult></cus_checkResponse></soap:Body></soap:Envelope>
事實說明,這里其實是個NSString類型的谦去,并不是服務(wù)器反給我們的JSON慷丽,因為前面還是帶接口中的標(biāo)簽,如果要是直接使用里面的JSON格式數(shù)據(jù)鳄哭,那么你就悲催了要糊,什么都不會拿到的;所以妆丘,我們在這里需要用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];
我們看一下打印的結(jié)果,截取后的字符串
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":"已導(dǎo)入","user_name":"王峻","ut":"袋"}]
沒錯了勺拣,這個就是我們要的結(jié)果奶赠,但它仍然是個字符串
3.使用NSString轉(zhuǎn)NSData
NSString *requestTmp = [NSString stringWithString:resultString];
NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
大家看一下第2點的打印結(jié)果,JSON格式無疑药有,那么除去[ ]中括號是標(biāo)準(zhǔn)JSON格式的樣例毅戈,包在數(shù)據(jù)外層的是{ }大括號苹丸,所以對應(yīng)的就是字典!
OK了苇经,下面接簡單了赘理,字典接數(shù)據(jù),根據(jù)打印結(jié)果建立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什么都不寫商模。。
總結(jié)
希望大家喜歡我寫的東西蜘澜,轉(zhuǎn)發(fā)收藏什么的施流,多多益善~
上面的所有代碼都是復(fù)制粘貼我自己的,有些類名兼都、變量名嫂沉、參數(shù)名都是我后改的,有可能改錯了扮碧,但是我相信趟章,細(xì)心的你一定會發(fā)現(xiàn)。
最后慎王,如果你有更好的蚓土,請回復(fù)我,并粘貼你的資料地址赖淤。
有事私信
WangJun 20170222