首先新建类WebServices
WebServices.h
#import <Foundation/Foundation.h> @interface WebServiceHelper : NSObject @property (nonatomic,strong) NSString *MethodName; @property (nonatomic,strong) NSString *SoapUrlAddress; @property (nonatomic,strong) NSMutableDictionary *MethodKeyAndValues; @property (nonatomic,strong) NSString *XmlNameSpace; -(NSString *)Post; @end
WebServices.m
#import "WebServiceHelper.h" @implementation WebServiceHelper - (instancetype)init { self = [super init]; if (self) { self.SoapUrlAddress=@"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx"; self.XmlNameSpace=@"http://WebXml.com.cn/"; } return self; } -(NSString *)Post { NSString *xml=[[NSString alloc]init]; NSMutableString *soapMsg=[[NSMutableString alloc]init]; [soapMsg appendFormat:@"<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" "]; [soapMsg appendFormat:@"xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body>"]; [soapMsg appendFormat:@"<%@ xmlns="%@">",self.MethodName,self.XmlNameSpace]; NSArray *keys=[self.MethodKeyAndValues allKeys]; int length=[keys count]; for (int i=0; i<length; i++) { id key=[keys objectAtIndex:i]; id value=[self.MethodKeyAndValues objectForKey:key]; [soapMsg appendFormat:@"<%@>%@</%@>",key,value,key]; } [soapMsg appendFormat:@"</%@></soap:Body></soap:Envelope>",self.MethodName]; NSLog(@"%@",soapMsg); NSURL *url=[NSURL URLWithString:self.SoapUrlAddress]; NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:url]; [req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; NSString *soapAction=[[NSString alloc]initWithFormat:@"%@%@",self.XmlNameSpace,self.MethodName]; [req addValue:soapAction forHTTPHeaderField:@"SOAPAction"]; NSLog(@"%@",soapAction); [req setHTTPMethod:@"POST"]; [req setHTTPBody:[soapMsg dataUsingEncoding:NSUTF8StringEncoding]]; NSURLResponse *response=nil; NSError *error=nil; NSData *result=[NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error]; if (error) { NSLog(@"Connection Error: %@", [error description], nil); } xml=[[NSString alloc]initWithData:result encoding:NSUTF8StringEncoding]; return xml; } @end
调用方法
WebServiceHelper *helper=[[WebServiceHelper alloc]init]; helper.MethodName=@"getMobileCodeInfo"; NSMutableDictionary *keyAndValues=[NSMutableDictionary dictionaryWithObjectsAndKeys:@"123456789",@"mobileCode",@"",@"userid",nil]; helper.MethodKeyAndValues=keyAndValues; NSString *value=[helper Post]; NSLog(@"%@",value);
与前一个比的好处就是,不用委托了。因为是初学,大家多提意见。