您的位置:首页 > 移动开发 > IOS开发

iOS下WebService接口调用与解析-一、Soap对象的封装

2017-03-24 17:15 495 查看

封装Soap对象

Soap对象是对请求体的简单封装,免去重复而又容易出错的拼接工作。

首先是头文件:SOAPMessage.h

#import <Foundation/Foundation.h>

@interface SOAPMessage : NSObject

@property (nonatomic, strong) NSString *nameSpace;
@property (nonatomic, strong) NSString *methodName;
@property (nonatomic, strong) NSDictionary *params;

- (SOAPMessage *)initWithNameSpace:(NSString *)nameSpace withMethodName:(NSString *)method withParams:(NSDictionary *)params;

/**
* 创建SOAP消息,内容格式就是网站上提示的请求报文的实体主体部分
*/
- (NSString *)getSoapMessage;

@end


头文件中,定义了三个属性,分别为:

nameSpace:命名空间

methodName:方法名

params:方法名对应的参数列表

一个初始化方法:

- (SOAPMessage )initWithNameSpace:(NSString )nameSpace withMethodName:(NSString )method withParams:(NSDictionary )params;

包含三个参数,对应定义的三个属性。

最后一个方法的作用是将封装后的SOAP类型的xml对象转换成NSString。

然后是实现:SOAPMessage.m

#import "SOAPMessage.h"

@interface SOAPMessage ()

- (NSString *) generateMethod;
- (NSString *) generateParams:(NSDictionary *)dict;

@end

@implementation SOAPMessage

- (SOAPMessage *)initWithNameSpace:(NSString *)nameSpace withMethodName:(NSString *)methodName withParams:(NSDictionary *)params {
if(self =[super init]) {
self.nameSpace = nameSpace;
self.methodName = methodName;
self.params = params;
}

return self;
}

- (NSString *)getSoapMessage {

NSString *soapMsg = [NSString stringWithFormat:
@"<?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>"
"%@"
//"<say xmlns=\"http://service.core.soft.com\">"
//"<name>%@</name>"
//"</say>"
//"<getSupportCity xmlns=\"http://WebXml.com.cn/\">"
//"<byProvinceName>%@</byProvinceName>"
//"</getSupportCity>"
"</soap12:Body>"
"</soap12:Envelope>", [self generateMethod]];

return soapMsg;
}

- (NSString *) generateMethod {
NSString *result = [[NSString alloc] initWithFormat:@"<%@ xmlns=\"%@\">%@</%@>",
[self methodName],
[self nameSpace],
[self generateParams:[self params]],
[self methodName]];
return result;
}

- (NSString *) generateParams:(NSDictionary *)dic {
NSMutableString *params = [NSMutableString string];
for (id key in [dic allKeys]) {
NSString *param = @"<%@>%@</%@>";

NSString *p = [[NSString alloc]initWithFormat:param, key, [dic objectForKey:key], key];
[params appendString:p];
}
return params;
}
@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios 解析