美文网首页经验demo
iOS原生方法通过SOAP调用WebService

iOS原生方法通过SOAP调用WebService

作者: 辛乐 | 来源:发表于2016-09-19 23:34 被阅读208次
/**
 *  请求SOAP,返回NSData
 *
 *  @param url      请求地址
 *  @param soapBody soap的XML中方法和参数段
 *  @param success  成功block
 *  @param failure  失败block
 */
+ (void)SOAPData:(NSString *)url soapBody:(NSDictionary *)bodyParams success:(void (^)(id responseObject))success failure:(void(^)(NSError *error))failure {
    
    NSString *paramsStr = @"";
    
    for (NSString *key in bodyParams.allKeys) {
        
        if (![key isEqualToString:@"method"] ) {
            paramsStr = [NSString stringWithFormat:@"%@<%@>%@</%@>",paramsStr,key,bodyParams[key],key];
        }
        
    }
    
    //调用的方法 + (命名空间:这个对应wsdl文档的命名空间)
    NSString *bodyStr = [NSString stringWithFormat:
                         @"<%@ xmlns = \"http://tempuri.org/\">%@</%@>\n",bodyParams[@"method"],paramsStr,bodyParams[@"method"]];
    
    NSString *soapStr = [NSString stringWithFormat:
                         @"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                         "<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\">\n"
                         "<SOAP-ENV:Body>%@</SOAP-ENV:Body>\n"
                         "</SOAP-ENV:Envelope>\n",bodyStr];
    
    
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    
    NSString *msgLength = [NSString stringWithFormat:@"%lu", (unsigned long)[soapStr length]];
    
    //以下对请求信息添加属性前四句是必有的,第五句是soap信息。
    
    [request addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    //[request addValue: @"暂不设置,使用默认值" forHTTPHeaderField:@"SOAPAction"];
    
    [request addValue: msgLength forHTTPHeaderField:@"Content-Length"];
    
    [request setHTTPMethod:@"POST”];//因为body可能很长所以选择POST方式
     
     [request setHTTPBody: [soapStr dataUsingEncoding:NSUTF8StringEncoding]];
     
     NSURLSession *session = [NSURLSession sharedSession];
     
     //线程安全,显示小菊花作为网络的提示状态(HUDTool是对MBProgress进行了封装)
     dispatch_main_async_safe(^{
        
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [HUDTool showToView:app.window];
        
    });
     
     
     NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        dispatch_main_async_safe(^{
            
            AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [HUDTool hideForView:app.window];
            
        });
        
        
        NSString *result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
        
        if (error) {
            LOG(@"Session----失败----%@", error.localizedDescription);
            if (failure) {
                
                dispatch_main_async_safe(^{
                    failure(error);
                });
                
            }
            
        }else{
            
            LOG(@"进入成功回调Session-----结果:%@----请求地址:%@", result, response.URL);
            
            NSError *error = nil;
            GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithData:data error:&error];
            
            //获取根节点 及中间所有的节点 GDataXMLElement类表示节点
            //获取根节点
            GDataXMLElement *rootElement = [document rootElement];
            
            //追踪到有效父节点 Result(分析返回结果的XML与当前调用方法的规律)
            //1.第一层soap:body解析
            GDataXMLElement *soapBody=[[rootElement elementsForName : @"soap:Body" ] objectAtIndex : 0 ];
            //2.第二层不同方法的Response解析
            GDataXMLElement *response=[[soapBody elementsForName :[NSString stringWithFormat:@"%@Response",bodyParams[@"method"]]] objectAtIndex : 0 ];
            //3.第三层不同方法的Result解析
            GDataXMLElement *result=[[response elementsForName :[NSString stringWithFormat:@"%@Result",bodyParams[@"method"]]] objectAtIndex : 0 ];
            
            NSMutableDictionary *resultDic = [NSMutableDictionary dictionaryWithCapacity:1];
            
            NSArray *arr = result.children;
            
            if (result.childCount == 1) {
                
                [resultDic setValue:[result stringValue] forKey:@"result"];
                
            }else{
                
                for (GDataXMLElement *element in arr) {
                    
                    NSString *str = [[[result elementsForName:element.name] objectAtIndex : 0 ] stringValue ];
                    if (str != nil) {
                        [resultDic setValue:str forKey:element.name];
                    }
                    
                }
                
            }
            
            if (success) {
                dispatch_main_async_safe(^{
                    success(resultDic);
                });
            }
        }
    }];
     
     [task resume];
     
     }

相关文章

网友评论

    本文标题:iOS原生方法通过SOAP调用WebService

    本文链接:https://www.haomeiwen.com/subject/gownettx.html