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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,837評論 18 139
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,740評論 18 399
  • 生長在江南水鄉,雨水充裕,然而,我不喜歡雨。 下雨天多麻煩啊,要帶傘,傘又是易耗品,轉頭就落在了別人家。上學騎車,...
    盒子很隨心閱讀 724評論 1 11
  • 雙十一來襲,商家的打折廣告鋪天蓋地,商品信息也極顯誘惑力,購物狂們不安分心開始躁動起來,購物車的各類物品琳瑯滿目。...
    幽蘭小姐閱讀 414評論 0 1
  • 1. 你是不是經常收到這類信息? “你也清清吧,不用回,不要讓拉黑你的人占用你的空間”,有時候我一天能收到好幾條這...
    沈善書閱讀 2,408評論 8 27