iOS原生方法通過SOAP調用WebService

/**
 *  請求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];
     
     }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容