iOS 与webService

来源:互联网 发布:三轴点胶机编程教学 编辑:程序博客网 时间:2024/06/05 10:10

前几日做了一个小项目,后台是web服务,之前没接触过,后来找了很多资料最终解决,链接web服务不想链接webAPI,给个链接就行了,web服务需要拼接请求报文,其中要拼接头部

如 

 "Content-Length" = 421;//包体长度    "Content-Type" = "text/xml; charset=utf-8";//类型    Host = "www.XXXXXXXX.com";//主机链接    soapAction = "http://tempuri.org/IAppService/DataOperate";//调用的方法
这个是请求的head

接下来就是拼接body里的内容

<?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:Body><DataOperate xmlns="http://tempuri.org/"><span style="color:#ff9900;"><strjson></span><span style="color:#ff0000;">{"funCode":"1101","funParams":"{\"pushNumber\":0,\"userId\":\"4A2D8F8FE0A84532A60EA31B8CB8ABE5\"}"}</span></strjson></DataOperate></soap:Body></soap:Envelope> 是不是很奇怪这串红色的内容,其实就是需要拼接参数,这个和其他的webservice的请求不太一样,这里是要给服务器拼接一串json字符串,当时搞了很久才弄好,<pre name="code" class="objc"><span style="color:#ff9900;"><strjson>是参数便签</span>
<span style="color:#ff9900;"></span>

这些弄好后就需要请求了,使用第三方AF和苹果自带的都行,下面我贴出我的请求代码

        //任意一个控制器内请求
    [arr addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat: @"{\"funCode\":\"1101\",\"funParams\":\"{%@:%d,%@:%@}\"}",@"\\\"pushNumber\\\"",0,@"\\\"userId\\\"",@"\\\"4A2D8F8FE0A84532A60EA31B8CB8ABE5\\\""] ,@"strjson", nil]];    NSString *soapMsg=[SoapHelper arrayToDefaultSoapMessage:arr methodName:@"DataOperate"];    [helper asyncServiceMethod:@"DataOperate" soapMessage:soapMsg];    

#import <Foundation/Foundation.h>@interface SoapHelper : NSObject//默认soap信息+(NSString*)defaultSoapMesage;//生成soap信息+(NSString*)methodSoapMessage:(NSString*)methodName;+(NSString*)nameSpaceSoapMessage:(NSString*)space methodName:(NSString*)methodName;//有参数soap生成+(NSString*)arrayToDefaultSoapMessage:(NSArray*)arr methodName:(NSString*)methodName;+(NSString*)arrayToNameSpaceSoapMessage:(NSString*)space params:(NSArray*)arr methodName:(NSString*)methodName;@end

////  SoapHelper.m//  HttpRequest/**** //SOAP Envelope GDataXMLElement *envelope = [GDataXMLElement elementWithName:@"soap:Envelope"];  GDataXMLNode *soapNS = [GDataXMLNode namespaceWithName:@"soap" stringValue:@"http://schemas.xmlsoap.org/soap/envelope/"]; GDataXMLNode *xsiNS = [GDataXMLNode namespaceWithName:@"xsi" stringValue:@"http://www.w3.org/2001/XMLSchema-instance"]; GDataXMLNode *xsdNS = [GDataXMLNode namespaceWithName:@"xsd" stringValue:@"http://www.w3.org/2001/XMLSchema"]; GDataXMLNode *defaultNS = [GDataXMLNode namespaceWithName:@"" stringValue:@"http://60.251.51.217/ElandMC.Admin/WebServices/"];  NSArray *namespaces = [NSArray arrayWithObjects:xsiNS, xsdNS, soapNS, nil]; [envelope setNamespaces:namespaces];  //SOAP Body GDataXMLElement *body = [GDataXMLElement elementWithName:@"soap:Body"];  //SOAP Value GDataXMLElement *value = [GDataXMLElement elementWithName:@"getProductAd"]; [value addNamespace:defaultNS]; [body addChild:value];  [envelope addChild:body];  //SOAP Document GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithRootElement:envelope]; [doc setCharacterEncoding:@"utf-8"];  NSLog(@"doc = %@", [NSString stringWithCString:(const char *)[[doc XMLData] bytes] encoding:NSUTF8StringEncoding]); [doc release]; ****///  ////#import "SoapHelper.h"@implementation SoapHelper+(NSString*)defaultSoapMesage{    NSString *soapBody=@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"    "<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/\">\n"    "<soap:Body>%@</soap:Body></soap:Envelope>";    return soapBody;}+(NSString*)methodSoapMessage:(NSString*)methodName{    NSMutableString *soap=[NSMutableString stringWithFormat:@"<%@ xmlns=\"%@\">",methodName,defaultWebServiceNameSpace];    [soap appendString:@"%@"];    [soap appendFormat:@"</%@>",methodName];    return [NSString stringWithFormat:[self defaultSoapMesage],soap];}+(NSString*)nameSpaceSoapMessage:(NSString*)space methodName:(NSString*)methodName{    NSMutableString *soap=[NSMutableString stringWithFormat:@"<%@ xmlns=\"%@\">",methodName,space];    [soap appendString:@"%@"];    [soap appendFormat:@"</%@>",methodName];    return [NSString stringWithFormat:[self defaultSoapMesage],soap];}+(NSString*)arrayToDefaultSoapMessage:(NSArray*)arr methodName:(NSString*)methodName{    if ([arr count]==0||arr==nil) {        return [NSString stringWithFormat:[self methodSoapMessage:methodName],@""];    }    NSMutableString *msg=[NSMutableString stringWithFormat:@""];    for (NSDictionary *item in arr) {        NSString *key=[[item allKeys] objectAtIndex:0];         [msg appendFormat:@"<%@>",key];                [msg appendString:[item objectForKey:key]];        [msg appendFormat:@"</%@>",key];    }    return [NSString stringWithFormat:[self methodSoapMessage:methodName],msg];}+(NSString*)arrayToNameSpaceSoapMessage:(NSString*)space params:(NSArray*)arr methodName:(NSString*)methodName{    if ([arr count]==0||arr==nil) {        return [NSString stringWithFormat:[self nameSpaceSoapMessage:space methodName:methodName],@""];    }    NSMutableString *msg=[NSMutableString stringWithFormat:@""];    for (NSDictionary *item in arr) {        NSString *key=[[item allKeys] objectAtIndex:0];        [msg appendFormat:@"<%@>",key];        [msg appendString:[item objectForKey:key]];        [msg appendFormat:@"</%@>",key];    }    return [NSString stringWithFormat:[self nameSpaceSoapMessage:space methodName:methodName],msg];}@end

////  WebServices.h//  HttpRequest////////#import <Foundation/Foundation.h>//异步调用完成的协议@protocol WebServiceDelegate <NSObject>@optional-(void)requestFinishedMessage:(NSString*)xml;-(void)requestFailedMessage:(NSError*)error;@end@interface WebServices : NSObject@property(nonatomic,retain) NSMutableData *receivedData;@property (nonatomic,assign) id<WebServiceDelegate> delegate;-(id)initWithDelegate:(id<WebServiceDelegate>)thedelegate;//公有方法-(NSMutableURLRequest*)commonRequestUrl:(NSString*)wsUrl nameSpace:(NSString*)space methodName:(NSString*)methodname soapMessage:(NSString*)soapMsg;+(NSMutableURLRequest*)commonSharedRequestUrl:(NSString*)wsUrl nameSpace:(NSString*)space methodName:(NSString*)methodname soapMessage:(NSString*)soapMsg;//同步调用-(NSString*)syncServiceUrl:(NSString*)wsUrl nameSpace:(NSString*)space methodName:(NSString*)methodname soapMessage:(NSString*)soapMsg;-(NSString*)syncServiceMethod:(NSString*)methodName soapMessage:(NSString*)soapMsg;//异步调用-(void)asyncServiceUrl:(NSString*)wsUrl nameSpace:(NSString*)space methodName:(NSString*)methodname soapMessage:(NSString*)soapMsg;-(void)asyncServiceMethod:(NSString*)methodName soapMessage:(NSString*)soapMsg;@end


////  WebServices.m//  HttpRequest////  ////#import "WebServices.h"#import "SoapXmlParseHelper.h"@implementation WebServices@synthesize delegate;@synthesize receivedData;-(id)initWithDelegate:(id<WebServiceDelegate>)thedelegate{    if (self=[super init]) {        self.delegate=thedelegate;    }    return self;}-(NSMutableURLRequest*)commonRequestUrl:(NSString*)wsUrl nameSpace:(NSString*)space methodName:(NSString*)methodname soapMessage:(NSString*)soapMsg{        NSURL *url=[NSURL URLWithString:wsUrl];    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];    NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMsg length]];    NSString *soapAction=[NSString stringWithFormat:@"%@IAppService/%@",space,methodname];    //头部设置    NSDictionary *headField=[NSDictionary dictionaryWithObjectsAndKeys:[url host],@"Host",                             @"text/xml; charset=utf-8",@"Content-Type",                             msgLength,@"Content-Length",                             soapAction,@"soapAction",nil];    [request setAllHTTPHeaderFields:headField];    NSLog(@"head头部: %@",headField);    //超时设置    [request setTimeoutInterval: 30 ];    //访问方式    [request setHTTPMethod:@"POST"];    //body内容    [request setHTTPBody:[soapMsg dataUsingEncoding:NSUTF8StringEncoding]];    return request;     }+(NSMutableURLRequest*)commonSharedRequestUrl:(NSString*)wsUrl nameSpace:(NSString*)space methodName:(NSString*)methodname soapMessage:(NSString*)soapMsg{    NSURL *url=[NSURL URLWithString:wsUrl];    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];          NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMsg length]];    NSString *soapAction=[NSString stringWithFormat:@"%@%@",space,methodname];    //头部设置    NSDictionary *headField=[NSDictionary dictionaryWithObjectsAndKeys:[url host],@"Host",                             @"application/soap+xml; charset=utf-8",@"Content-Type",                             msgLength,@"Content-Length",                             soapAction,@"SOAPAction",nil];    [request setAllHTTPHeaderFields:headField];        //超时设置    [request setTimeoutInterval: 30 ];    //访问方式    [request setHTTPMethod:@"POST"];    //body内容    [request setHTTPBody:[soapMsg dataUsingEncoding:NSUTF8StringEncoding]];    return request;}#pragma -#pragma 同步调用-(NSString*)syncServiceUrl:(NSString*)wsUrl nameSpace:(NSString*)space methodName:(NSString*)methodname soapMessage:(NSString*)soapMsg{          NSMutableURLRequest *request=[self commonRequestUrl:wsUrl nameSpace:space methodName:methodname soapMessage:soapMsg];    NSError *err=nil;    NSHTTPURLResponse *urlResponse = nil;     NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&err];    if (err||urlResponse.statusCode!=200) {        return @"";    }    return [SoapXmlParseHelper SoapMessageResultXml:data ServiceMethodName:methodname];}-(NSString*)syncServiceMethod:(NSString*)methodName soapMessage:(NSString*)soapMsg{        return [self syncServiceUrl:defaultWebServiceUrl nameSpace:defaultWebServiceNameSpace methodName:methodName soapMessage:soapMsg];}#pragma -#pragma 异步调用-(void)asyncServiceUrl:(NSString*)wsUrl nameSpace:(NSString*)space methodName:(NSString*)methodname soapMessage:(NSString*)soapMsg{    NSMutableURLRequest *request =[self commonRequestUrl:wsUrl nameSpace:space methodName:methodname soapMessage:soapMsg];    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];    if(conn ){        self.receivedData = [NSMutableData data];    }}-(void)asyncServiceMethod:(NSString*)methodName soapMessage:(NSString*)soapMsg{  //  NSLog(@"请求SOAP信息 %@:",soapMsg);    [self asyncServiceUrl:defaultWebServiceUrl nameSpace:defaultWebServiceNameSpace methodName:methodName soapMessage:soapMsg];    }#pragma mark -#pragma mark NSURLConnection delegate Methods- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{[self.receivedData setLength:0];}- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{        [self.receivedData appendData:data];}- (void)connection:(NSURLConnection *)connection  didFailWithError:(NSError *)error{    connection = nil;    self.receivedData = nil;    [self.delegate requestFailedMessage:error];}- (void)connectionDidFinishLoading:(NSURLConnection *)connection{   NSDictionary *dic=connection.currentRequest.allHTTPHeaderFields;    NSString *soapAction=[dic objectForKey:@"soapAction"];NSString *methodName=[soapAction stringByReplacingOccurrencesOfString:defaultWebServiceNameSpace withString:@""];        NSString *theXML = [[NSString alloc] initWithBytes:[self.receivedData mutableBytes]                                                length:[self.receivedData length]                                              encoding:NSUTF8StringEncoding];        //NSLog(@"%@",theXML);    if ([self.delegate respondsToSelector:@selector(requestFinishedMessage:)]) {        [self.delegate requestFinishedMessage:[SoapXmlParseHelper SoapMessageResultXml:self.receivedData ServiceMethodName:@"DataOperateResponse"]];                connection = nil;    }   }-(void)dealloc{    }@end

//webservice配置#define defaultWebServiceUrl @"http://www.zhuozhu100.com:81/AppService.svc"#define defaultWebServiceNameSpace @"http://tempuri.org/"



记得导入gdXML解析
////  XmlParseHelper.h//  HttpRequest////  Created by rang on 12-11-10.////#import <Foundation/Foundation.h>#import "GDataXMLNode.h"@interface SoapXmlParseHelper : NSObject/******************************webservice调用返回的xml处理*****************************************//****   **获取webservice调用返回的xml内容   **data:为NSData或NSString   **methodName:调用的webservice方法名 ***/+(NSString*)SoapMessageResultXml:(id)xml ServiceMethodName:(NSString*)methodName;/******************************xml转换成数组处理**************************************************//*****   **xml转换成Array   **xml:NSData或NSString *****/+(NSMutableArray*)XmlToArray:(id)xml;/*****   **xml节点转换成Array *****/+(NSMutableArray*)nodeChilds:(GDataXMLNode*)node;/******************************xml节点查询处理**************************************************//*****   **查找指定节点保存到数组中   **data:NSData或NSString   **name:节点名称 *****/+(NSMutableArray*)SearchNodeToArray:(id)data nodeName:(NSString*)name;/*****   **查找指定节点保存到数组中   **data:NSData或NSString   **name:节点名称   **className:对象名称 *****/+(NSMutableArray*)SearchNodeToObject:(id)data nodeName:(NSString*)name objectName:(NSString*)className;/******************************xml操作辅助方法**************************************************//*****   **获取当前节点下的所有子节点保存到字典中 *****/+(NSMutableDictionary*)ChildsNodeToDictionary:(GDataXMLNode*)node;/*****   **获取当前节点下的所有子节点保存到对象中 *****/+(id)ChildsNodeToObject:(GDataXMLNode*)node objectName:(NSString*)className;/******************************xml根节点操作**************************************************///获取根节点下的子节点+(NSMutableDictionary*)rootNodeToArray:(id)data;+(id)rootNodeToObject:(id)data objectName:(NSString*)className;@end


<pre name="code" class="objc">////  XmlParseHelper.m//  HttpRequest////  Created by rang on 12-11-10.////#import "SoapXmlParseHelper.h"#import "GDataXMLNode.h"@implementation SoapXmlParseHelper#pragma mark -#pragma mark 获取methodName+Result里面的内容/****   **获取webservice调用返回的xml内容   **data:为NSData或NSString   **methodName:调用的webservice方法名 ***/+(NSString*)SoapMessageResultXml:(id)data ServiceMethodName:(NSString*)methodName{    NSError *error=nil;    GDataXMLDocument *document;    if ([data isKindOfClass:[NSString class]]) {        document=[[GDataXMLDocument alloc] initWithXMLString:data options:0 error:&error];    }else{        document=[[GDataXMLDocument alloc] initWithData:data options:0 error:&error];    }    if (error) {        [document release];        return @"";    }    GDataXMLElement* rootNode = [document rootElement];    NSString *searchStr=[NSString stringWithFormat:@"%@",methodName];    NSString *MsgResult=@"";    NSArray *result=[rootNode children];    while ([result count]>0) {        NSString *nodeName=[[result objectAtIndex:0] name];        if ([nodeName isEqualToString: searchStr]) {            MsgResult=[[result objectAtIndex:0] stringValue];            break;        }        result=[[result objectAtIndex:0] children];    }    [document release];    return MsgResult;}#pragma mark -#pragma mark 将xml转换成数组/***** **xml转换成Array **xml:NSData或NSString *****/+(NSMutableArray*)XmlToArray:(id)xml{    NSMutableArray *arr=[NSMutableArray array];    NSError *error=nil;    GDataXMLDocument *document;    if ([xml isKindOfClass:[NSString class]]) {        document=[[GDataXMLDocument alloc] initWithXMLString:xml options:0 error:&error];    }    else       document=[[GDataXMLDocument alloc] initWithData:xml options:0 error:&error];    if (error) {        [document release];        return arr;    }    GDataXMLElement* rootNode = [document rootElement];    NSArray *rootChilds=[rootNode children];    for (GDataXMLNode *node in rootChilds) {        NSString *nodeName=node.name;        if ([node.children count]>0) {            [arr addObject:[NSDictionary dictionaryWithObjectsAndKeys:[self nodeChilds:node],nodeName, nil]];        }else{            [arr addObject:[NSDictionary dictionaryWithObjectsAndKeys:[node stringValue],nodeName, nil]];        }    }    [document release];    return arr;}+(NSMutableArray*)nodeChilds:(GDataXMLNode*)node{    NSMutableArray *arr=[NSMutableArray array];    NSArray *childs=[node children];    NSMutableDictionary *dic=[NSMutableDictionary dictionary];    for (GDataXMLNode* child in childs){        NSString *nodeName=child.name;//获取节点名称        NSArray  *childNode=[child children];        if ([childNode count]>0) {//存在子节点            [dic setValue:[self nodeChilds:child] forKey:nodeName];        }else{            [dic setValue:[child stringValue] forKey:nodeName];        }    }    [arr addObject:dic];    return arr;}#pragma mark -#pragma mark xml查询处理/*****   **查找指定节点保存到数组中   **data:NSData或NSString   **name:节点名称 *****/+(NSMutableArray*)SearchNodeToArray:(id)data nodeName:(NSString*)nodeName{    NSMutableArray *array=[NSMutableArray array];    NSError *error=nil;    GDataXMLDocument *document;    if ([data isKindOfClass:[NSString class]]) {        data=[data stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"xmlns=\"%@\"",nodeName] withString:@""];        document=[[GDataXMLDocument alloc] initWithXMLString:data options:0 error:&error];    }else{        document=[[GDataXMLDocument alloc] initWithData:data options:0 error:&error];    }    if (error) {        [document release];        return array;    }    NSString *searchStr=[NSString stringWithFormat:@"//%@",nodeName];    GDataXMLElement* rootNode = [document rootElement];    NSArray *childs=[rootNode nodesForXPath:searchStr error:nil];    for (GDataXMLNode *item in childs){        [array addObject:[self ChildsNodeToDictionary:item]];    }    [document release];    return array;}/***** **查找指定节点保存到数组中 **data:NSData或NSString **name:节点名称 **className:对象名称 *****/+(NSMutableArray*)SearchNodeToObject:(id)data nodeName:(NSString*)name objectName:(NSString*)className{    NSMutableArray *array=[NSMutableArray array];    NSError *error=nil;    GDataXMLDocument *document;    if ([data isKindOfClass:[NSString class]]) {        data=[data stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"xmlns=\"%@\"",name] withString:@""];        document=[[GDataXMLDocument alloc] initWithXMLString:data options:0 error:&error];    }else{        document=[[GDataXMLDocument alloc] initWithData:data options:0 error:&error];    }    if (error) {        [document release];        return array;    }    NSString *searchStr=[NSString stringWithFormat:@"//%@",name];    GDataXMLElement* rootNode = [document rootElement];    NSArray *childs=[rootNode nodesForXPath:searchStr error:nil];    for (GDataXMLNode *item in childs){        [array addObject:[self ChildsNodeToObject:item objectName:className]];    }    [document release];    return array;}#pragma mark -#pragma mark xml操作辅助方法+(NSMutableDictionary*)ChildsNodeToDictionary:(GDataXMLNode*)node{    NSMutableDictionary *dic=[NSMutableDictionary dictionary];    NSArray *childs=[node children];    for (GDataXMLNode *item in childs) {        [dic setValue:[item stringValue] forKey:item.name];    }    return dic;}+(id)ChildsNodeToObject:(GDataXMLNode*)node objectName:(NSString*)className{    id obj=[[NSClassFromString(className) alloc] init];    NSArray *childs=[node children];    for (GDataXMLNode *item in childs){        SEL sel=NSSelectorFromString(item.name);        if ([obj respondsToSelector:sel]) {            [obj setValue:[item stringValue] forKey:item.name];        }    }    return [obj autorelease];}#pragma mark -#pragma mark 对于xml只有一个根节点的处理+(NSMutableDictionary*)rootNodeToArray:(id)data{    NSMutableDictionary *dic=[NSMutableDictionary dictionary];    NSError *error=nil;    GDataXMLDocument *document;    if ([data isKindOfClass:[NSString class]]) {        document=[[GDataXMLDocument alloc] initWithXMLString:data options:0 error:&error];    }else{        document=[[GDataXMLDocument alloc] initWithData:data options:0 error:&error];    }    if (error) {        [document release];        return dic;    }    GDataXMLElement* rootNode = [document rootElement];    NSArray *rootChilds=[rootNode children];    for (GDataXMLNode *item in rootChilds){        [dic setValue:[item stringValue] forKey:item.name];    }    [document release];    return dic;}+(id)rootNodeToObject:(id)data objectName:(NSString*)className{    id obj=[NSClassFromString(className) new];    NSError *error=nil;    GDataXMLDocument *document;    if ([data isKindOfClass:[NSString class]]) {        document=[[GDataXMLDocument alloc] initWithXMLString:data options:0 error:&error];    }else{        document=[[GDataXMLDocument alloc] initWithData:data options:0 error:&error];    }    if (error) {        [document release];        return obj;    }    GDataXMLElement* rootNode = [document rootElement];    NSArray *rootChilds=[rootNode children];    for (GDataXMLNode *item in rootChilds){        SEL sel=NSSelectorFromString(item.name);        if ([obj respondsToSelector:sel]) {            [obj setValue:[item stringValue] forKey:item.name];        }    }    [document release];    return obj;}@end





0 0
原创粉丝点击