封装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
本文介绍了一个用于简化SOAP请求创建过程的Objective-C类。该类通过封装请求体,避免了手动拼接SOAP请求时可能出现的错误。文章详细展示了SOAPMessage类的设计与实现。

1335

被折叠的 条评论
为什么被折叠?



