iOS調(diào)用webservice -- 【W(wǎng)J】

注意:

本文主要介紹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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末蜀漆,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子咱旱,更是在濱河造成了極大的恐慌确丢,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,548評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件吐限,死亡現(xiàn)場離奇詭異鲜侥,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)诸典,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評論 3 399
  • 文/潘曉璐 我一進(jìn)店門描函,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人狐粱,你說我怎么就攤上這事舀寓。” “怎么了肌蜻?”我有些...
    開封第一講書人閱讀 167,990評論 0 360
  • 文/不壞的土叔 我叫張陵互墓,是天一觀的道長。 經(jīng)常有香客問我宋欺,道長轰豆,這世上最難降的妖魔是什么胰伍? 我笑而不...
    開封第一講書人閱讀 59,618評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮酸休,結(jié)果婚禮上骂租,老公的妹妹穿的比我還像新娘。我一直安慰自己斑司,他們只是感情好渗饮,可當(dāng)我...
    茶點故事閱讀 68,618評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著宿刮,像睡著了一般互站。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上僵缺,一...
    開封第一講書人閱讀 52,246評論 1 308
  • 那天胡桃,我揣著相機(jī)與錄音,去河邊找鬼磕潮。 笑死翠胰,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的自脯。 我是一名探鬼主播之景,決...
    沈念sama閱讀 40,819評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼膏潮!你這毒婦竟也來了锻狗?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,725評論 0 276
  • 序言:老撾萬榮一對情侶失蹤焕参,失蹤者是張志新(化名)和其女友劉穎轻纪,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體叠纷,經(jīng)...
    沈念sama閱讀 46,268評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡桐磁,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,356評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了讲岁。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,488評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡衬以,死狀恐怖缓艳,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情看峻,我是刑警寧澤阶淘,帶...
    沈念sama閱讀 36,181評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站互妓,受9級特大地震影響溪窒,放射性物質(zhì)發(fā)生泄漏坤塞。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,862評論 3 333
  • 文/蒙蒙 一澈蚌、第九天 我趴在偏房一處隱蔽的房頂上張望摹芙。 院中可真熱鬧,春花似錦宛瞄、人聲如沸浮禾。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,331評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽盈电。三九已至,卻和暖如春杯活,著一層夾襖步出監(jiān)牢的瞬間匆帚,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,445評論 1 272
  • 我被黑心中介騙來泰國打工旁钧, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留吸重,地道東北人。 一個月前我還...
    沈念sama閱讀 48,897評論 3 376
  • 正文 我出身青樓均践,卻偏偏與公主長得像晤锹,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子彤委,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,500評論 2 359

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理鞭铆,服務(wù)發(fā)現(xiàn),斷路器焦影,智...
    卡卡羅2017閱讀 134,696評論 18 139
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法车遂,類相關(guān)的語法,內(nèi)部類的語法斯辰,繼承相關(guān)的語法舶担,異常的語法,線程的語...
    子非魚_t_閱讀 31,662評論 18 399
  • 生長在江南水鄉(xiāng)彬呻,雨水充裕衣陶,然而,我不喜歡雨闸氮。 下雨天多麻煩啊剪况,要帶傘,傘又是易耗品蒲跨,轉(zhuǎn)頭就落在了別人家译断。上學(xué)騎車,...
    盒子很隨心閱讀 713評論 1 11
  • 雙十一來襲翎蹈,商家的打折廣告鋪天蓋地淮菠,商品信息也極顯誘惑力,購物狂們不安分心開始躁動起來杨蛋,購物車的各類物品琳瑯滿目兜材。...
    幽蘭小姐閱讀 408評論 0 1
  • 1. 你是不是經(jīng)常收到這類信息? “你也清清吧逞力,不用回曙寡,不要讓拉黑你的人占用你的空間”,有時候我一天能收到好幾條這...
    沈善書閱讀 2,388評論 8 27