你的位置:首页 > 操作系统

[操作系统]ASI

ASIHTTPRequest 虽然是明日黄花,但是还是稍微归纳一下,理清思路,知道这个曾经的她都能干嘛。

 

1. ASI基于底层的 CFNetworking 框架,运行效率很高。

2. 黄金搭档:ASI + SBJson ,ASI用来网络请求,SBJson用来解析服务器返回的数据。

3.ASI的使用参考:

1> 宝玉的博客:

http://www.cnblogs.com/dotey/archive/2011/05/10/2041966.html
 
2> oxchina.net开源中国社区
http://www.oschina.net/question/54100_36184

 

 

基本使用:

1.发送同步请求;

包含主文件 #import "ASIHTTPRequest.h"// 1.创建请求NSURL *url = [NSURL URLWithString:@"http://192.168.1.111:8080/XZServer/login?username=123&pwd=123"];ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];request.timeOutSeconds = 5; // 超时// 2.发送同步请求[request startSynchronous];// 3.获得错误信息NSError *error = [request error];if (error) {  NSLog(@"出错了");} else {  // 获得服务器的响应    NSData *data = [request responseData];} // [request responseData]

 

2.发送异步请求;

// 1.创建请求NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/XZServer/login?username=123456&pwd=123456"];ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];request.timeOutSeconds = 5; // 超时// 2.设置代理request.delegate = self;// 3.发送异步请求[request startAsynchronous];// ASI通过代理的方式处理异步请求,请求成功、失败都会通知代理//  代理需要遵守ASIHTTPRequestDelegate协议

 

3.ASIHTTPRequestDelegate:

接收到服务器的数据就调用- (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data请求失败就调用- (void)requestFailed:(ASIHTTPRequest *)request请求成功完毕就调用- (void)requestFinished:(ASIHTTPRequest *)request注意:应当在控制器被销毁的时候,取消请求[request clearDelegatesAndCancel];

 

ASI 的 SEL 回调:

@property (atomic, assign) SEL didStartSelector;@property (atomic, assign) SEL didReceiveResponseHeadersSelector;@property (atomic, assign) SEL willRedirectSelector;@property (atomic, assign) SEL didFinishSelector;@property (atomic, assign) SEL didFailSelector;@property (atomic, assign) SEL didReceiveDataSelector;

 

ASI 的 block 回调:

- (void)setStartedBlock:(ASIBasicBlock)aStartedBlock;- (void)setHeadersReceivedBlock:(ASIHeadersBlock)aReceivedBlock;- (void)setCompletionBlock:(ASIBasicBlock)aCompletionBlock;- (void)setFailedBlock:(ASIBasicBlock)aFailedBlock;- (void)setBytesReceivedBlock:(ASIProgressBlock)aBytesReceivedBlock;- (void)setBytesSentBlock:(ASIProgressBlock)aBytesSentBlock;- (void)setDownloadSizeIncrementedBlock:(ASISizeBlock) aDownloadSizeIncrementedBlock;- (void)setUploadSizeIncrementedBlock:(ASISizeBlock) anUploadSizeIncrementedBlock;- (void)setDataReceivedBlock:(ASIDataBlock)aReceivedBlock;- (void)setAuthenticationNeededBlock:(ASIBasicBlock)anAuthenticationBlock;- (void)setProxyAuthenticationNeededBlock:(ASIBasicBlock)aProxyAuthenticationBlock;- (void)setRequestRedirectedBlock:(ASIBasicBlock)aRedirectBlock;typedef void (^ASIBasicBlock)(void);typedef void (^ASIHeadersBlock)(NSDictionary *responseHeaders);typedef void (^ASISizeBlock)(long long size);typedef void (^ASIProgressBlock)(unsigned long long size, unsigned long long total);typedef void (^ASIDataBlock)(NSData *data);

 

获得服务器的响应:

获得状态码\状态信息@property (atomic, assign,readonly) int responseStatusCode;@property (atomic, retain,readonly) NSString *responseStatusMessage;获得响应头@property (atomic, retain) NSDictionary *responseHeaders;获得实体内容(响应体)- (NSData *)responseData;- (NSString *)responseString;

 

发送POST请求:

包含头文件:#import "ASIFormDataRequest.h"// 1.创建请求NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/XZServer/login"];ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];// 2.设置请求参数[request addPostValue:@"123" forKey:@"username"];[request addPostValue:@"123" forKey:@"pwd"];// 注意addPostValue和setPostValue的区别

 

文件上传:

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];// 添加普通的请求参数[request addPostValue:@"MJ" forKey:@"username"];// 添加文件参数NSString *file = [[NSBundle mainBundle] pathForResource:@"musicplayer.png" ofType:nil];[request addFile:file forKey:@"file"];// 或者UIImage *image = [UIImage imageNamed:@"musicplayer"];NSData *data = UIImagePNGRepresentation(image);[request addData:data withFileName:@"test.png" andContentType:@"image/png" forKey:@"file"];

文件上传 – 添加文件参数

有2种添加文件参数的方法:1>通过文件的全路径- (void)addFile:(NSString *)filePath forKey:(NSString *)key- (void)addFile:(NSString *)filePath withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key2>通过文件的具体数据- (void)addData:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key

 

 

文件下载:

// 设置缓存路径NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];NSString *filepath = [caches stringByAppendingPathComponent:@"test.mp4"];request.downloadDestinationPath = filepath;// 设置下载代理request.downloadProgressDelegate = self.progressView;大文件支持断点续传// 设置文件的临时路径request.temporaryFileDownloadPath = tmpFilepath;// 设置支持断点续传request.allowResumeForFileDownloads = YES;

监听文件上传\下载进度

成为ASI的代理- (void)setUploadProgressDelegate:(id)newDelegate遵守ASIProgressDelegate协议,实现协议方法- (void)setProgress:(float)newProgress;

 

缓存:

ASI也提供了数据缓存功能它只对Get请求的响应数据进行缓存被缓存的数据必需是成功的200请求使用ASIDownloadCache类管理缓存常见ASIDownloadCache用法取得默认的缓存对象ASIDownloadCache *cache = [ASIDownloadCache sharedCache];设置缓存策略- (void)setDefaultCachePolicy:(ASICachePolicy)cachePolicy设置缓存路径- (void)setStoragePath:(NSString *)path

 

缓存策略 - ASICachePolicy

缓存策略:什么时候进行缓存,缓存数据的利用方式。可用组合使用默认缓存策略:如果存在未过期的缓存数据,则使用缓存;否则进行网络请求,判断服务器版本与本地版本是否一样,如果一样,则使用缓存。
如果服务器有新版本,会进行网络请求,并更新本地缓存ASIUseDefaultCachePolicyASIAskServerIfModifiedWhenStaleCachePolicy与默认缓存大致一样,区别仅是每次请求都会 去服务器判断是否有更新ASIAskServerIfModifiedCachePolicy不读取缓存数据ASIDoNotReadFromCacheCachePolicy不缓存数据,不写缓存ASIDoNotWriteToCacheCachePolicy如果有缓存,不管其过期与否,总会拿来使用,没有缓存就重新请求ASIOnlyLoadIfNotCachedCachePolicy有缓存,拿来使用,如果没有缓存,请求将被取消(没有错误信息)ASIDontLoadCachePolicy请求失败时,如果有缓存则返回缓存(经常被用来与其它选项组合使用)ASIFallbackToCacheIfLoadFailsCachePolicy

 

 缓存某个请求:

// 设置缓存策略ASIDownloadCache *cache = [ASIDownloadCache sharedCache];[cache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy | ASIFallbackToCacheIfLoadFailsCachePolicy];// 使用缓存[request setDownloadCache:cache];// 设置缓存的存储策略(永久存储)[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];

 

 

ASIHTTPRequest缓存的存储策略

缓存的存储策略:缓存需要保存多长时间默认策略,基于session的缓存数据存储,当下次运行或[ASIHTTPRequest clearSession]时,缓存将失效(内存缓存)ASICacheForSessionDurationCacheStoragePolicy缓存数据永久保存在本地(硬盘缓存)ASICachePermanentlyCacheStoragePolicy

 

缓存所有请求:

// 设置缓存策略ASIDownloadCache *cache = [ASIDownloadCache sharedCache];[cache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy | ASIFallbackToCacheIfLoadFailsCachePolicy];// 使用缓存[ASIHTTPRequest setDefaultCache:cache];

 

缓存的其他特性:

设置缓存的有效期[request setSecondsToCache:60 * 60 * 24 * 7]; // 缓存7天判断数据是否从缓存读取的BOOL useCache = [request didUseCachedResponse];

 

ASIHTTPRequest 其他特性:

实际上ASIHTTPRequest继承自NSOperation,意味着可以将多个 ASIHTTPRequest 放到NSOperationQueue中,同时管理多个请求可以设置请求之间的依赖… …ASIFormDataRequest 继承自 ASIHTTPRequest

 

其他用法:

现在是否有网络请求在处理中[ASIHTTPRequest isNetworkInUse];当正在请求时,是否要在状态栏显示联网状态(转圈圈)[ASIHTTPRequest setShouldUpdateNetworkActivityIndicator:YES];当应用后台运行时,是否仍然继续处理网络请求request.shouldContinueWhenAppEntersBackground = YES;设置请求超时后重试的次数request.numberOfTimesToRetryOnTimeout = 2; // 重试2次