ios--请求接口并解析xml

来源:互联网 发布:淘宝美工工作总结 编辑:程序博客网 时间:2024/06/10 20:30

工具类:

1、请求接口要用到的工具类:webservice

webservice.h

#import <Foundation/Foundation.h>#import "XMLParser.h"#import "WeiboSDK/WeiboSDK.h"@interface webservice : NSObject<MBProgressHUDDelegate>{    MBProgressHUD *HUD;}-(NSDictionary *)insertCatalogWithJsonForJson:(NSURL*)strurl send:(NSDictionary *)sendinfo;-(TreeNode *)insertCatalogWithJson:(NSURL*)strurl send:(NSDictionary *)sendinfo;-(TreeNode *)insertCatalogWithJsondata:(NSURL*)strurl send:(NSData *)sendinfo;-(TreeNode *)insertCatalogWithJsonmul:(NSURL*)strurl send:(NSMutableDictionary *)sendinfo ;-(void *)getxmldata:(TreeNode *)node  receive:(NSMutableArray *)arrreceive  result:(NSMutableArray *)resultarry;@property (strong, nonatomic) IBOutlet UIView *fatherview;@property (nonatomic) bool show;@property (nonatomic) bool errorconnect;@end

webservice.m

#import "webservice.h"#import "AppDelegate.h"@implementation webservice//傳送至web Service-(NSDictionary *)insertCatalogWithJsonForJson:(NSURL*)strurl send:(NSDictionary *)sendinfo {    NSLog(@"strurl=%@,dic=%@",[strurl debugDescription],[sendinfo debugDescription]);    NSError *error = NULL;    //壓縮成NSData,這時的編碼會成UTF8格式    NSData *jsonData = [NSJSONSerialization                        dataWithJSONObject:sendinfo                        options:NSJSONWritingPrettyPrinted                        error:&error];        NSString *urlAsString = [[NSString alloc]initWithString: [strurl absoluteString]];    urlAsString = [urlAsString stringByAppendingString:@"?action=insert"];        NSURL *url = [NSURL URLWithString:urlAsString];        NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];    [urlRequest setTimeoutInterval:50.0f];    [urlRequest setHTTPMethod:@"POST"];    //直接把NSData(這時的編碼為UTF8)做為傳送的內容    [urlRequest setHTTPBody:jsonData];    NSURLResponse *response = nil;    NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest                                         returningResponse:&response error:&error];        if ([data length] >0 && error == nil)    {        //获得到数据        NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];                NSLog(@"html = %@",html);                NSData *data1 = [html dataUsingEncoding:NSUTF8StringEncoding];        //NSLog(@"data1 = %@", [data1 debugDescription]);                NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&error];        NSMutableArray *arr=[dic mutableArrayValueForKey:@"jsonOK"];        return [arr objectAtIndex:0];        //return node;    }else if ([data length] == 0 && error == nil)    {        NSLog(@"Nothing was downloaded.");            }    else if (error != nil)    {        NSLog(@"Error happened = %@", error);        //if ([error code]==-1009) {        [self errordo:[error localizedDescription]];        //}    }    return nil;}//傳送至web Service-(TreeNode *)insertCatalogWithJson:(NSURL*)strurl send:(NSDictionary *)sendinfo {        NSError *error = NULL;    //壓縮成NSData,這時的編碼會成UTF8格式    NSData *jsonData = [NSJSONSerialization                        dataWithJSONObject:sendinfo                        options:NSJSONWritingPrettyPrinted                        error:&error];    NSString *urlAsString = [[NSString alloc]initWithString: [strurl absoluteString]];    urlAsString = [urlAsString stringByAppendingString:@"?action=insert"];        NSURL *url = [NSURL URLWithString:urlAsString];        NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];    [urlRequest setTimeoutInterval:50.0f];    [urlRequest setHTTPMethod:@"POST"];    //直接把NSData(這時的編碼為UTF8)做為傳送的內容    [urlRequest setHTTPBody:jsonData];    NSURLResponse *response = nil;        NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest                                         returningResponse:&response error:&error];        if ([data length] >0 && error == nil)    {        //  使用下面代码获取web服务器上的xml,并将xml转换成树:        XMLParser *parser = [[XMLParser alloc] init];        // NSURL * url = [[NSURL alloc] initWithString:@"Login.xml"];        TreeNode *node = [parser parseXMLFromData:data];        //NSLog(@"node = %@", [node debugDescription]);        return node;    }else if ([data length] == 0 && error == nil)    {        NSLog(@"Nothing was downloaded.");            }    else if (error != nil)    {        NSLog(@"Error happened = %@", error);        //if ([error code]==-1009) {        [self errordo:[error localizedDescription]];        //}    }    return nil;}-(TreeNode *)insertCatalogWithJsonmul:(NSURL*)strurl send:(NSMutableDictionary *)sendinfo {        NSError *error = NULL;    //壓縮成NSData,這時的編碼會成UTF8格式    NSData *jsonData = [NSJSONSerialization                        dataWithJSONObject:sendinfo                        options:NSJSONWritingPrettyPrinted                        error:&error];    NSLog(@"%@",error);    NSString *urlAsString = [[NSString alloc]initWithString: [strurl absoluteString]];    urlAsString = [urlAsString stringByAppendingString:@"?action=insert"];        NSURL *url = [NSURL URLWithString:urlAsString];        NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];    [urlRequest setTimeoutInterval:30.0f];    [urlRequest setHTTPMethod:@"POST"];    //直接把NSData(這時的編碼為UTF8)做為傳送的內容    [urlRequest setHTTPBody:jsonData];    NSURLResponse *response = nil;        NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest                                         returningResponse:&response error:&error];        if ([data length] >0 && error == nil)    {        //  使用下面代码获取web服务器上的xml,并将xml转换成树:        XMLParser *parser = [[XMLParser alloc] init];        // NSURL * url = [[NSURL alloc] initWithString:@"Login.xml"];        TreeNode *node = [parser parseXMLFromData:data];                return node;    }else if ([data length] == 0 && error == nil)    {        NSLog(@"Nothing was downloaded.");            }    else if (error != nil)    {        NSLog(@"Error happened = %@", error);        //if ([error code]==-1009) {        [self errordo:[error localizedDescription]];        //}    }    return nil;}-(TreeNode *)insertCatalogWithJsondata:(NSURL*)strurl send:(NSData *)sendinfo {        NSError *error = NULL;    NSString *urlAsString = [[NSString alloc]initWithString: [strurl absoluteString]];    urlAsString = [urlAsString stringByAppendingString:@"&action=insert"];    NSURL *url = [NSURL URLWithString:urlAsString];        NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];    [urlRequest setTimeoutInterval:20.0f];    [urlRequest setHTTPMethod:@"POST"];    //直接把NSData(這時的編碼為UTF8)做為傳送的內容    [urlRequest setHTTPBody:sendinfo];        NSURLResponse *response = nil;        NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest                                         returningResponse:&response error:&error];        if ([data length] >0 && error == nil)    {        //  使用下面代码获取web服务器上的xml,并将xml转换成树:        XMLParser *parser = [[XMLParser alloc] init];        // NSURL * url = [[NSURL alloc] initWithString:@"Login.xml"];        TreeNode *node = [parser parseXMLFromData:data];                return node;    }else if ([data length] == 0 && error == nil)    {        NSLog(@"Nothing was downloaded.");            }    else if (error != nil)    {        NSLog(@"Error happened = %@", error);        //if ([error code]==-1009) {            [self errordo:[error localizedDescription]];        //}    }    return nil;}-(void *)getxmldata:(TreeNode *) node receive:(NSMutableArray *)arrreceive  result:(NSMutableArray *)resultarry{       // NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];        //      NSMutableArray *dataarry = [[NSMutableArray alloc] init];        //   NSLog(@"HTML = %@", html);                        //获取xml中的登录结果:        for(NSString *string in arrreceive)        {            NSRange range;            range=[string rangeOfString:@"#"];            if (range.length ==0) {                NSString * strkey=[node leafForKey:string];                if (strkey ==nil) {                    strkey = @"";                }                NSString * result = [[NSString alloc] initWithString:strkey];                //   NSLog(@"result=%@",result);                if ([result isEqual:nil]||[result isEqualToString:@""]) {                    continue;                }                [resultarry addObject:result];            }            else            {                //类似xpath去取值:                NSArray *array = [string componentsSeparatedByString:@"#"];                NSString * result =  [[NSString alloc] initWithString:[node leafForKeys:array]];                //     NSLog(@"result=%@",result);                if ([result isEqual:nil]||[result isEqualToString:@""]) {                    continue;                }                [resultarry addObject:result];            }        }        //重新從WebService讀取資料        //     [self wsLookingFun];    }- (void)errordo:(NSString *)content {// Do something usefull in here instead of sleeping ...//sleep(1);    self.errorconnect=true;    if (!self.show) {        AppDelegate *appDelegate=[[UIApplication sharedApplication] delegate];        [appDelegate.crtabBarController performSelectorOnMainThread:@selector(errordo:) withObject:content waitUntilDone:YES];    }      //  UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:content delegate:self  cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];  //  [alter show];}- (void)myTask {// Do something usefull in here instead of sleeping ...sleep(3);}@end


2、xml解析要用到两个工具类:XMLParser和TreeNode

XMLParser.h

#import <CoreFoundation/CoreFoundation.h>#import "TreeNode.h"@interface XMLParser : NSObject{    NSMutableArray      *stack;}+ (XMLParser *) sharedInstance;- (TreeNode *) parseXMLFromURL: (NSURL *) url;- (TreeNode *) parseXMLFromData: (NSData*) data;@end


XMLParser.m

#import "XMLParser.h"@implementation XMLParserstatic XMLParser *sharedInstance = nil;// Use just one parser instance at any time+(XMLParser *) sharedInstance{    if(!sharedInstance) {        sharedInstance = [[self alloc] init];    }    return sharedInstance;}// Parser returns the tree root. You may have to go down one node to the real results- (TreeNode *) parse: (NSXMLParser *) parser{    stack = [NSMutableArray array];    TreeNode *root = [TreeNode treeNode];    root.parent = nil;    root.leafvalue = nil;    root.children = [NSMutableArray array];    [stack addObject:root];    [parser setDelegate:self];    [parser parse];//    [parser release];    // pop down to real root    TreeNode *realroot = [[root children] lastObject];    root.children = nil;    root.parent = nil;    root.leafvalue = nil;    root.key = nil;    realroot.parent = nil;    return realroot;}- (TreeNode *)parseXMLFromURL: (NSURL *) url{    TreeNode *results;//    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];    results = [self parse:parser];//    [pool drain];    return results;}- (TreeNode *)parseXMLFromData: (NSData *) data{    TreeNode *results;//    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];    results = [self parse:parser];//    [pool drain];    return results;}// Descend to a new element- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{    if (qName) elementName = qName;    TreeNode *leaf = [TreeNode treeNode];    leaf.parent = [stack lastObject];    [(NSMutableArray *)[[stack lastObject] children] addObject:leaf];    leaf.key = [NSString stringWithString:elementName];    leaf.leafvalue = nil;    leaf.children = [NSMutableArray array];    [stack addObject:leaf];}// Pop after finishing element- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{    [stack removeLastObject];}// Reached a leaf- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{    if (![[stack lastObject] leafvalue])    {        [[stack lastObject] setLeafvalue:[NSString stringWithString:string]];        return;    }    [[stack lastObject] setLeafvalue:[NSString stringWithFormat:@"%@%@", [[stack lastObject] leafvalue], string]];}@end

TreeNode.h

#import <CoreFoundation/CoreFoundation.h>@interface TreeNode : NSObject{    TreeNode        *parent;    NSMutableArray  *children;    NSString        *key;    NSString        *leafvalue;}@property (nonatomic, retain)   TreeNode        *parent;@property (nonatomic, retain)   NSMutableArray  *children;@property (nonatomic, retain)   NSString        *key;@property (nonatomic, retain)   NSString        *leafvalue;@property (nonatomic, readonly) BOOL            isLeaf;@property (nonatomic, readonly) BOOL            hasLeafValue;@property (nonatomic, readonly) NSArray         *keys;@property (nonatomic, readonly) NSArray         *allKeys;@property (nonatomic, readonly) NSArray         *uniqKeys;@property (nonatomic, readonly) NSArray         *uniqAllKeys;@property (nonatomic, readonly) NSArray         *leaves;@property (nonatomic, readonly) NSArray         *allLeaves;@property (nonatomic, readonly) NSString        *dump;+ (TreeNode *) treeNode;- (NSString *) dump;- (void) teardown;// Leaf Utils- (BOOL) isLeaf;- (BOOL) hasLeafValue;- (NSArray *) leaves;- (NSArray *) allLeaves;// Key Utils- (NSArray *) keys;- (NSArray *) allKeys;- (NSArray *) uniqKeys;- (NSArray *) uniqAllKeys;// Search Utils- (TreeNode *) objectForKey: (NSString *) aKey;- (NSString *) leafForKey: (NSString *) aKey;- (NSMutableArray *) objectsForKey: (NSString *) aKey;- (NSMutableArray *) leavesForKey: (NSString *) aKey;- (TreeNode *) objectForKeys: (NSArray *) keys;- (NSString *) leafForKeys: (NSArray *) keys;- (NSMutableArray *) childrenForKeys: (NSArray *) keys;// Convert Utils- (NSMutableDictionary *) dictionaryForChildren;@end

TreeNode.m

#import "TreeNode.h"// String stripper utility macro#define STRIP(X)    [X stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]@implementation TreeNode@synthesize parent;@synthesize children;@synthesize key;@synthesize leafvalue;#pragma mark Create and Initialize TreeNodes- (TreeNode *) init{    if (self = [super init])    {        self.key = nil;        self.leafvalue = nil;        self.parent = nil;        self.children = nil;    }    return self;}+ (TreeNode *) treeNode{    return [[self alloc] init];}#pragma mark TreeNode type routines- (BOOL) isLeaf{    return (self.children.count == 0);}- (BOOL) hasLeafValue{    return (self.leafvalue != nil);}#pragma mark TreeNode data recovery routines// Return an array of child keys. No recursion- (NSArray *) keys{    NSMutableArray *results = [NSMutableArray array];    for (TreeNode *node in self.children) [results addObject:node.key];    return results;}// Return an array of child keys with depth-first recursion.- (NSArray *) allKeys{    NSMutableArray *results = [NSMutableArray array];    for (TreeNode *node in self.children)    {        [results addObject:node.key];        [results addObjectsFromArray:node.allKeys];    }    return results;}- (NSArray *) uniqArray: (NSArray *) anArray{    NSMutableArray *array = [NSMutableArray array];    for (id object in [anArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)])        if (![[array lastObject] isEqualToString:object]) [array addObject:object];    return array;}// Return a sorted, uniq array of child keys. No recursion- (NSArray *) uniqKeys{    return [self uniqArray:[self keys]];}// Return a sorted, uniq array of child keys. With depth-first recursion- (NSArray *) uniqAllKeys{    return [self uniqArray:[self allKeys]];}// Return an array of child leaves. No recursion- (NSArray *) leaves{    NSMutableArray *results = [NSMutableArray array];    for (TreeNode *node in self.children) if (node.leafvalue) [results addObject:node.leafvalue];    return results;}// Return an array of child leaves with depth-first recursion.- (NSArray *) allLeaves{    NSMutableArray *results = [NSMutableArray array];    for (TreeNode *node in self.children)    {        if (node.leafvalue) [results addObject:node.leafvalue];        [results addObjectsFromArray:node.allLeaves];    }    return results;}#pragma mark TreeNode search and retrieve routines// Return the first child that matches the key, searching recursively breadth first- (TreeNode *) objectForKey: (NSString *) aKey{    TreeNode *result = nil;    for (TreeNode *node in self.children)        if ([node.key isEqualToString: aKey])        {            result = node;            break;        }    if (result) return result;    for (TreeNode *node in self.children)    {        result = [node objectForKey:aKey];        if (result) break;    }    return result;}// Return the first leaf whose key is a match, searching recursively breadth first- (NSString *) leafForKey: (NSString *) aKey{    TreeNode *node = [self objectForKey:aKey];    return node.leafvalue;}// Return all children that match the key, including recursive depth first search.- (NSMutableArray *) objectsForKey: (NSString *) aKey{    NSMutableArray *result = [NSMutableArray array];    for (TreeNode *node in self.children)    {        if ([node.key isEqualToString: aKey])            [result addObject:node];        [result addObjectsFromArray:[node objectsForKey:aKey]];    }    return result;}// Return all leaves that match the key, including recursive depth first search.- (NSMutableArray *) leavesForKey: (NSString *) aKey{    NSMutableArray *result = [NSMutableArray array];    for (TreeNode *node in [self objectsForKey:aKey])        if (node.leafvalue)            [result addObject:node.leafvalue];    return result;}// Follow a key path that matches each first found branch, returning object- (TreeNode *) objectForKeys: (NSArray *) keys{    if ([keys count] == 0) return self;    NSMutableArray *nextArray = [NSMutableArray arrayWithArray:keys];    [nextArray removeObjectAtIndex:0];    for (TreeNode *node in self.children)    {        if ([node.key isEqualToString:[keys objectAtIndex:0]])            return [node objectForKeys:nextArray];    }    return nil;}//获取指定节点下的所有子节点- (NSMutableArray *) childrenForKeys: (NSArray *) keys{    TreeNode *fathernode = [self objectForKeys:keys];    NSMutableArray *result = [NSMutableArray array];    for (TreeNode *node in fathernode.children)    {        NSMutableDictionary * dictionary = [[NSMutableDictionary alloc] init];                dictionary = [node dictionaryForChildren];        [result addObject:dictionary];      //  [result addObjectsFromArray:[node childrenForKeys:keys]];    }    return result;}// Follow a key path that matches each first found branch, returning leaf- (NSString *) leafForKeys: (NSArray *) keys{    TreeNode *node = [self objectForKeys:keys];    return node.leafvalue;}#pragma mark output utilities// Print out the tree- (void) dumpAtIndent: (int) indent into:(NSMutableString *) outstring{    for (int i = 0; i < indent; i++) [outstring appendString:@"--"];    [outstring appendFormat:@"[%2d] Key: %@ ", indent, key];    if (self.leafvalue) [outstring appendFormat:@"(%@)", STRIP(self.leafvalue)];    [outstring appendString:@"\n"];    for (TreeNode *node in self.children) [node dumpAtIndent:indent + 1 into: outstring];}- (NSString *) dump{    NSMutableString *outstring = [[NSMutableString alloc] init];    [self dumpAtIndent:0 into:outstring];    return outstring ;}#pragma mark conversion utilities// When you're sure you're the parent of all leaves, transform to a dictionary- (NSMutableDictionary *) dictionaryForChildren{    NSMutableDictionary *results = [NSMutableDictionary dictionary];    for (TreeNode *node in self.children)        if (node.hasLeafValue) [results setObject:node.leafvalue forKey:node.key];    return results;}#pragma mark invocation forwarding// Invocation Forwarding lets node act like array- (id)forwardingTargetForSelector:(SEL)sel{    if ([self.children respondsToSelector:sel]) return self.children;    return nil;}// Extend selector compliance- (BOOL)respondsToSelector:(SEL)aSelector{    if ( [super respondsToSelector:aSelector] ) return YES;    if ([self.children respondsToSelector:aSelector]) return YES;    return NO;}// Allow posing as NSArray class for children- (BOOL)isKindOfClass:(Class)aClass{    if (aClass == [TreeNode class]) return YES;    if ([super isKindOfClass:aClass]) return YES;    if ([self.children isKindOfClass:aClass]) return YES;    return NO;}#pragma mark cleanup- (void) teardown{    for (TreeNode *node in [self.children copy]) [node teardown];    [self.parent.children removeObject:self];    self.parent = nil;}- (void) dealloc{    self.parent = nil;    self.children = nil;    self.key = nil;    self.leafvalue = nil; }@end

调用接口获取xml数据并解析xml:

    anticounterfeitSections = [[NSMutableArray alloc] initWithObjects:nil];//用来与UITableViewSection对应    [anticounterfeitSections addObject:@""];    webservice *service=  [[webservice alloc] init];    NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:                          value,@"key",                          nil];//请求参数    NSURL *strurl = [NSURL URLWithString:urlString];//请求网址 NSURL类型    //完成Json格式後,進行新增    TreeNode *refdata= [[TreeNode alloc] init];    refdata=[service insertCatalogWithJson:strurl send:info];//将请求到的数据以TreeNode格式存放到refdata    service=nil;//请求完毕后,释放webservice类    //[NSThread sleepForTimeInterval:3];    NSMutableDictionary * rootdic = [refdata dictionaryForChildren];//根目录下面的节点集    NSLog(@"info=%@",[rootdic objectForKey:@"Info"]);//打印该节点集里面的名称为Info的节点的value    NSMutableArray *test = [[NSMutableArray alloc] initWithObjects:                            @"items",                            nil];//定义一个名称为items的节点集    //获取地址列表    NSMutableArray * test1 = [refdata childrenForKeys:test];//从该节点集里面读取到名称为items的节点集    refdata=nil;//释放    NSMutableArray *demaxiyaHeros = [[NSMutableArray alloc] init];    NSLog(@"%@",test1);    if ([[rootdic objectForKey:@"isSuccess"] isEqualToString:@"1"]) {        for (NSMutableDictionary *dic in test1) {           //to-do        }        anticounterfeitData = [[NSMutableArray alloc] initWithObjects:demaxiyaHeros, nil];//将items里面的每个item解析并放入NSMutableArray类型中    }


0 0