soap字符串格式
<?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:Header>
</soap:Header>
<soap:Body> //这里面才是重点
<方法名 xmlns="webservice命名空间">
<参数名>值</参数名>
<参数名>值</参数名>
</方法名>
</soap:Body>
</soap:Envelope>
按上面的格式拼接soap字符串soapMessage,然后就可以请求了
NSString *soapMessage = @"";
NSURL *url = [NSURL URLWithString:webUrl];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%lu", (unsigned long)[soapMessage length]];
//可有可无 有默认值
// [theRequest addValue: @"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
// [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:theRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
self.failureBlock(error);
} else {
//请求出来的结果是xml格式,解析
[self parseXML:data];
}
}];
[task resume];
请求结果示例
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:xxx xmlns:ns2="xxx">
<return>
<rslt>
<ret_code>xxx</ret_code>
<ret_msg>xxx</ret_msg>
<ret_result_cnt>xxx</ret_result_cnt>
</rslt>
<rslt>
xxx
</rslt>
</return>
</ns2:xxx>
</soap:Body>
</soap:Envelope>
使用kissXML解析xml
NSString *rsltStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
rsltStr = [self stringByDecodingHTMLEntitiesInString:rsltStr];
//KissXML是基于DOM的解析方式
DDXMLDocument *rsltDoc = [[DDXMLDocument alloc] initWithXMLString:rsltStr options:0 error:nil];
//XPath是XML中的定位语法,可以快速定位到Xml中的节点或者属性;
//"//xx" 表示从整个xml文档中查找,而不考虑当前节点位置
NSArray *rsltArr = [rsltDoc nodesForXPath:@"//rslt" error:nil];
NSXMLElement *rslt = nil;
if (rsltArr.count > 0) {
rslt = rsltArr[0];
}
NSString *ret_code = [[rslt elementForName:@"ret_code"] stringValue];
NSString *ret_msg = [[rslt elementForName:@"ret_msg"] stringValue];
NSString *ret_result_cnt = [[rslt elementForName:@"ret_result_cnt"] stringValue];
NSDictionary *dic = @{@"code":ret_code,@"msg":ret_msg,@"cnt":ret_result_cnt};
self.successBlock(dic);
但是我的请求结果却是这样的:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:xxx xmlns:ns2="xxx">
<return><rslt><ret_code>xxx</ret_code><ret_msg>xxx</ret_msg><ret_result_cnt>xxx</ret_result_cnt></rslt></return>
</ns2:xxx>
</soap:Body>
</soap:Envelope>
所以在开始之前有个方法stringByDecodingHTMLEntitiesInString将字符串转换一下:
string = [string stringByReplacingOccurrencesOfString:@"<" withString:@"<"];
string = [string stringByReplacingOccurrencesOfString:@">" withString:@">"];