iOS-基于SOAP协议的WebService访问

SOAP(Simple Object Access Protocol)协议是一种基于XML的轻量级协议,用于WebService访问,WSDL(Web Services Description Language)是WebService的描述语言。

明确SOAP的格式:

<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>
        <方法名 xmlnx="方法URL">
        <参数名1>参数值</参数名1>
        <参数名2>参数值</参数名2>
        ...
        </方法名>
    </soap:Body>
</soap:Envelope>

如果WSDL定义了命名空间,需要替换成:

<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>
            <ws:方法名 xmlnx:ws="方法URL">
                <arg1>参数值</arg1>
                <arg0>参数值</arg0>
                ...
            </ws:方法名>
    </soap:Body>
</soap:Envelope>

Http访问

根据SOAP的格式生成对应的字符串后,可以进行Http访问,注意需要定义好一些属性。
具体如下:

NSURL *url = [NSURL URLWithString:SERVICE_URL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *requestString = [requestDict postXmlString];
[request addValue:XML forHTTPHeaderField:CONTENT_TYPE];
[request addValue:[NSString stringWithFormat:@"%@", @(requestString.length)] forHTTPHeaderField:CONTENT_LENGTH];
[request addValue:[url host] forHTTPHeaderField:HOST];
[request setHTTPMethod:POST];
[request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
void (^recallHandler)(NSURLResponse*, NSData*, NSError*) = ^(NSURLResponse *response, NSData *data, NSError *error){
    if ([data length] > 0 && error == nil) {
        NSDictionary *responseDict = [NSDictionary dictionaryWithResponseXMLString:[[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding]];
    }
};
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:recallHandler];

其中的宏定义为:

#define     SERVICE_URL     @"http://xxx?wsdl"
#define     XML             @"text/xml; charset=utf-8"
#define     CONTENT_TYPE    @"Content-Type"
#define     CONTENT_LENGTH  @"Content-Length"
#define     HOST            @"Host"
#define     POST            @"POST"

XML转换

XML和NSDictionary之间的互相转换可以参考XMLDictionary