因为工作上的需要,前后台的接口对接使用的webService进行的。本人之前的对接经验主要是webApi对接,返回JSON串进行处理。使用webService对接真心没有经验,更让我尴尬的是我之前就没听过webService这个名词。因为工作的需要以及弥补自己的不足,研究一下AF使用webService的请求。本人写的不好,大家多多见谅,希望能为同样经历的人提供一点帮助。
首先对AF进行初始化,我写的二次封装是继承于AFHTTPSessionManager写的。self与manager在调用方法上是一样的。
//初始化
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
//设置请求类型
manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
//设置请求超时时间
manager.requestSerializer.timeoutInterval = 30;
//设置这个的目的是返回信息成功后,信息为NSData类型,否则为NSXMLParser类型
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//这个一定要设置,否则会请求失败
[manager.requestSerializer setValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
//我参考了其他人的经验,但是以我的情况来说,使用“application/soap+xml”无法请求成功
// [manager.requestSerializer setValue:@"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"image/jpeg", @"text/plain", @"text/xml", nil];
这样webService的设置基本完成了,接下来需要按照各自的接口协议对参数进行设置,外部接口仍然按照NSDictionary的形式传进来,在二次封装内部进行处理
****特别注意:BaseUrl并非是完整的请求地址,只是域名部分末尾有“/”
//url:请求地址 dictionary:请求参数 action:方法名 successObject:成功回调 failureObject:失败回调 errorObject:异常回调
- (void)post_Url:(NSString *)url Param:(NSDictionary *)dictionary Action:(NSString *)action Success:(SuccessCompletedBlock)successObject Failure:(FailureCompletedBlock)failureObject Error:(ErrorCompletedBlock)errorObject {
NSMutableString *soapMutableStr = [self parameterToDealAction:action param:dictionary];
//请求发送到的路径
[self.requestSerializer setValue:[NSString stringWithFormat:@"%zd", soapMutableStr.length] forHTTPHeaderField:@"Content-Length"];
//设置HTTPBody
[self.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) {
return soapMutableStr;
}];
//数据请求
[self POST:url parameters:soapMutableStr progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//responseObject 一个NSData类型的文件
//数据的返回的具体格式是JSON类型(与后台协商后),需要封装个方法提取并转化为NSDictionary类型
NSDictionary *dict = [NSDictionary dictionaryWithDictionary:[CYTextTool webServiceDataExchangeDictionary:responseObject action:action]];
if (dict && [[dict objectForKey:@"status"] integerValue] == 0) {
//成功回调
if (successObject) {
successObject(dict);
}
}else {
//失败回调
if (failureObject) {
failureObject(dict);
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//异常回调
if (error) {
errorObject(error);
}
}];
}
下面是对整体参数的封装处理
- (NSMutableString *)parameterToDealAction:(NSString *)action param:(NSDictionary *)dictionary {
//Header为请求头 MineSoapHeader为方法名 key为参数(宏,是前后台内部定义的) BaseUrl为域名地址(宏)
NSString *headStr = [NSString stringWithFormat:
@"\n"
"\n"
"\n"
"\n"
"%@ \n"
" \n"
" \n" , BaseUrl, APP_KEY
];
//参数拼接
NSMutableString *soapMutableStr = [NSMutableString stringWithString:headStr];
//判断是否存在方法名
if (action.length > 0) {
//将body拼接上
[soapMutableStr appendString:[NSString stringWithFormat:@"\n"
"<%@ xmlns=\"%@\">\n", action, BaseUrl]];
}
//判断是否存在参数(如果存在参数一定会有方法名的)
if (dictionary) {
//将参数拼接进字符串中,格式value
for (NSString *key in dictionary) {
[soapMutableStr appendString:[NSString stringWithFormat:@"<%@>%@%@>\n", key, [dictionary objectForKey:key], key]];
}
}
//拼接body结束符
if (action.length > 0) {
[soapMutableStr appendString:[NSString stringWithFormat:@"%@>\n"" \n", action]];
}
//拼接整体请求结束符
[soapMutableStr appendString:@" \n"];
return soapMutableStr;
}
请求成功后对返回的数据进行处理,CYTextTool是自定义的工具类
//将NSData转化成NSDictionary
//data为返回文件 action为方法名
+ (NSDictionary *)webServiceDataExchangeDictionary:(NSData *)data action:(NSString *)action {
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// 利用正则表达式取出 之间的字符串
NSRegularExpression *regular = [[NSRegularExpression alloc] initWithPattern:[NSString stringWithFormat:@"(?<=%@Result\\>).*(?=%@Result)", action, action] options:NSRegularExpressionCaseInsensitive error:nil];
//创建接收字典
NSDictionary *dic = [NSDictionary dictionary];
for (NSTextCheckingResult *checkingResult in [regular matchesInString:result options:0 range:NSMakeRange(0, result.length)]) {
// 得到字典
dic = [NSJSONSerialization JSONObjectWithData:[[result substringWithRange:checkingResult.range] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
}
return dic;
}