ASIHTTPRequest 封装
jopen
11年前
iOS 网络请求常用第三方库ASI,使用方便。
调用方法: 一个请求和实现三个协议。
主要步骤:
1. 新建一个.h文件,用于新建枚举型和声明协议
标记post请求状态
//////////////////////////////////////////////////////////////////////////////////////// //TypeDefine.h //////////////////////////////////////////////////////////////////////////////////////// enum kPostStatus{ kPostStatusNone=0, kPostStatusBeging=1, kPostStatusEnded=2, kPostStatusError=3, kPostStatusReceiving=4 }; typedef enum kPostStatus kPostStatus; 页面请求ASI接口的标记 enum kBusinessTag { kBusinessTagDirectory= 0, //获取通讯录 kBusinessTagRootLogin=1, //首页登录 kBusinessTagGetUnits=2, //获取单位部门 kBusinessTagGetUnitPersons=3, //获取部门人员 kBusinessTagBinding=4, //进行设备绑定 kBusinessTagBindInfo=5, //获取绑定信息 kBusinessTagDynaPass=6, //获取动态密码 kBusinessTagSPLogin=7, //短信平台登录 kBusinessTagSPSendSMS=8, //群发短信 kBusinessTagQXTLogin=9, //企信通登录 kBusinessTagQXTMailList=10, //企信通收件箱 kBusinessTagQXTAttach=11, //企信通附件获取 kBusinessTagQXTMarkRead=12, //企信通标志已读 kBusinessTagQXTAddresses=13, //企信通获取收件人 kBusinessTagSPSmsRecords=14, //短信平台发送记录查询 kBusinessTagQXTSendMail=15, //企信通发送邮件 kBusinessTagVersion=16, //获取系统版本 kBusinessTagHelpInfo=17, //获取帮助文档 kBusinessTagModifySettings=18, //修改设置 kBusinessTagFeedback=19, //意见反馈 kBusinessTagUnlock=20, //解锁 kBusinessTagLog=21 , //记录日志 kBusinessUserIdential=22, //身份验证 kBusinessTagVersion_net=23, //外网获取系统版本 kAttenPubicMessage=24 , //获取发布信息 KsetInfoReadMessage=25, //已读信息回执设置 KFeedBackQuery = 26 //意见反馈查询 }; typedef enum kBusinessTag kBusinessTag; 声明一个协议,这个协议的三个方法在调用的页面实现 @protocol NetworkModuleDelegate<NSObject> @optional -(void)beginPost:(kBusinessTag)tag; -(void)endPost:(GDataXMLDocument*)result business:(NSNumber*)tag; -(void)errorPost:(NSError*)err business:(NSNumber*)tag; @end //////////////////////////////////////////////////////////////////////////////////////// //NetworkModule 类 //////////////////////////////////////////////////////////////////////////////////////// 2.新建一个网络模块 :NetworkModule 和 PostRequest //NetworkModule.h <ASIHTTPRequestDelegate>{ NSMutableDictionary* queue; } +(NetworkModule*)sharedNetworkModule; //单例 -(void)postBusinessReq:(NSString*)xml //UI调用接口 tag:(kBusinessTag)tag owner:(id<NetworkModuleDelegate>)owner; -(void)postXML:(NSString*)xml tag:(kBusinessTag)tag owner:(id<NetworkModuleDelegate>)owner url:(NSString*)url; -(void)cancel:(kBusinessTag)tag; //NetworkModule.m - (id)init { self = [super init]; if (self) { queue=[[NSMutableDictionary alloc]init]; } return self; } + (NetworkModule *)sharedNetworkModule { static NetworkModule *gInstance = NULL; @synchronized(self) { if (!gInstance) gInstance = [self new]; } return(gInstance); } -(void)postBusinessReq:(NSString*)xml //根据网络配置IP tag:(kBusinessTag)tag owner:(id<NetworkModuleDelegate>)owner{ NSMutableArray* arr=[[NSMutableArray alloc]init]; if ([[PingResult sharedPingResult]apnSuccess]) { [arr addObject:APN_IP]; }else if([[PingResult sharedPingResult]intraSuccess]){ [arr addObject:INTRA_IP]; }else{ [arr addObject: INTER_IP]; } NSString* s=[NSString stringWithFormat:@"SELF LIKE '%@'",server_ip]; NSPredicate* pre=[NSPredicate predicateWithFormat:s]; [arr filterUsingPredicate:pre]; if (arr.count>0){ [self postXML:xml tag:tag owner:owner url:[NSString stringWithFormat:interface_url,server_ip]]; }else{ if (owner) { NSError* err=[[NSError alloc]initWithDomain:ErrorDomain code:7001 userInfo:nil]; [owner errorPost:err business:[NSNumber numberWithInt:tag]]; } } [arr release]; } -(void)postXML:(NSString*)xml //外网地址 tag:(kBusinessTag)tag owner:(id<NetworkModuleDelegate>)owner url:(NSString*)url{ PostRequest* req=(PostRequest*)[queue objectForKey:[NSNumber numberWithInt:tag]]; if (req==nil) { req=[[PostRequest alloc]init]; } req.businessTag=tag; req.postStatus=kPostStatusNone; [queue setObject:req forKey:[NSNumber numberWithInt:tag]]; req.enc=NSUTF8StringEncoding; req.owner=owner; req.url=url; NSLog(@"%s:%@",__FUNCTION__,req.url); [req postXML:xml delegate:self]; } -(void)cancel:(kBusinessTag)tag{ PostRequest* req=(PostRequest*)[queue objectForKey:[NSNumber numberWithInt:tag]]; if (req && [req isKindOfClass:[PostRequest class]]) { [req cancel]; } } // 请求结束,获取 Response 数据 - (void)requestFinished:(ASIHTTPRequest *)request { PostRequest* req=(PostRequest*)[queue objectForKey: [NSNumber numberWithInt:request.tag]]; req.postStatus=kPostStatusEnded; if (req.owner!=nil) { SEL sel=@selector(endPost:business:); if ([req.owner respondsToSelector:sel]) { NSLog(@"result:==%@",req.result); [req.owner performSelector:sel withObject:req.result withObject:[NSNumber numberWithInt: req.businessTag]]; } } } // 请求失败,获取 error - (void)requestFailed:(ASIHTTPRequest *)request { PostRequest* req=(PostRequest*)[queue objectForKey: [NSNumber numberWithInt:request.tag]]; NSError *error = [request error]; NSLog(@"%s,%@",__FUNCTION__,error.userInfo); if (req.owner!=nil) { SEL sel=@selector(errorPost:business:); if ([req.owner respondsToSelector:sel]) { [req.owner performSelector:sel withObject:error withObject:[NSNumber numberWithInt: req.businessTag]]; } } } -(void)dealloc{ [queue release]; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////// //PostRequest类 //////////////////////////////////////////////////////////////////////////////////////// //PostRequest.h @interface PostRequest : NSObject{ ASIHTTPRequest* _request; id<NetworkModuleDelegate> owner; } @property (nonatomic,retain)id<NetworkModuleDelegate> owner; @property (nonatomic,retain)NSString* url; @property (assign)kPostStatus postStatus; @property (assign)kBusinessTag businessTag; @property (assign)NSStringEncoding enc; @property (nonatomic,readonly,getter = result)GDataXMLDocument* result;//用于请求后GData解析XML数据 -(void)cancel; -(void)postXML:(NSString*)xml delegate:(id)delegate; //PostRequest.m @implementation PostRequest @synthesize postStatus; @synthesize enc=_enc; @synthesize url; @synthesize businessTag=_tag; @synthesize owner; -(void)cancel{ if (_request!=nil) { [_request release],_request=nil; } } -(void)setOwner:(id<NetworkModuleDelegate>)_owner{ owner=[_owner retain]; } -(id<NetworkModuleDelegate>)owner{ return owner; } -(void)setEnc:(NSStringEncoding)enc{ _enc=enc; } -(NSStringEncoding)enc{ return _enc; } -(void)setBusinessTag:(kBusinessTag)businessTag{ _tag=businessTag; } -(kBusinessTag)businessTag{ return _tag; } -(GDataXMLDocument*)result{ if(postStatus==kPostStatusEnded){ NSData *data = [_request responseData]; NSString* string=[[NSString alloc] initWithData:data encoding:_enc]; NSLog(@"%s\nresponse:%@",__FUNCTION__,string); GDataXMLDocument* doc=[[GDataXMLDocument alloc] initWithXMLString: string options:0 error:nil]; return doc; }else return nil; } -(void)postXML:(NSString*)xml delegate:(id)delegate{ [self cancel]; _request=[[ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]]retain]; [_request setShouldAttemptPersistentConnection:NO]; [_request setResponseEncoding:_enc]; NSMutableDictionary *reqHeaders = [[NSMutableDictionary alloc] init]; [reqHeaders setValue:@"text/xml; charset=UTF-8" forKey:@"Content-Type"]; _request.requestHeaders = reqHeaders; [reqHeaders release]; NSLog(@"post xml:%@",xml); // 重要 _request.tag=_tag; [_request appendPostData:[xml dataUsingEncoding:_enc]]; [_request setDelegate:delegate]; postStatus=kPostStatusBeging; if(self.owner) [self.owner beginPost:self.businessTag]; [_request startAsynchronous]; } -(void)dealloc{ [owner release],owner=nil; [_request release]; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////// //请求调用 //////////////////////////////////////////////////////////////////////////////////////// 调用地方实现 NetworkModuleDelegate协议 NSString* postXML=SPSmsRecordsXml([[SPLoginInfo sharedSPLoginInfo]account], [[SPLoginInfo sharedSPLoginInfo]pass], beginDay,endDay); [[NetworkModule sharedNetworkModule]postBusinessReq:postXML tag:kBusinessTagSPSmsRecords owner:self];//请求 #pragma mark -NetworkModuleDelegate -(void)beginPost:(kBusinessTag)tag{ [indicator show:YES]; [indicator showMessage:@"正在获取数据" delay:1]; } -(void)endPost:(GDataXMLDocument *)result business:(NSNumber*)tag{ if (tag.intValue==kBusinessTagSPSmsRecords) { records=[[SmsRecordInfo alloc]initWithXMLElement:result.rootElement]; } [indicator showMessage:@"数据获取成功" delay:1]; } -(void)errorPost:(NSError *)err business:(NSNumber*)tag{ [indicator showMessage:@"网络错误" delay:1]; }