- 全稱是ASIHTTPRequest,外號“HTTP終結者”,功能十分強大
- 基於底層的CFNetwork框架,運行效率很高
- 可惜作者早已停止更新,有一些潛在的BUG無人去解決
- 很多公司的舊項目里面都殘留着它的身影,以前的很多iOS項目都是ASI + SBJson
- 會不會用ASI,可以算是檢驗是否為老牌iOS程序員的標准之一
ASI的github地址
https://github.com/pokeb/asi-http-request
ASI的使用參考
http://www.cnblogs.com/dotey/archive/2011/05/10/2041966.html
http://www.oschina.net/question/54100_36184
配置 – 導入源碼
配置 – 添加依賴類庫
發送同步請求
1 包含主文件 #import "ASIHTTPRequest.h" 2 // 1.創建請求 3 NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/MJServer/login?username=123&pwd=123"]; 4 ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 5 request.timeOutSeconds = 5; // 超時 6 // 2.發送同步請求 7 [request startSynchronous]; 8 // 3.獲得錯誤信息 9 NSError *error = [request error]; 10 if (error) { 11 NSLog(@"出錯了"); 12 } else { 13 // 獲得服務器的響應 14 NSData *data = [request responseData]; 15 } // [request responseData]
發送異步請求
1 // 1.創建請求 2 NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/MJServer/login?username=123&pwd=123"]; 3 ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 4 request.timeOutSeconds = 5; // 超時 5 6 // 2.設置代理 7 request.delegate = self; 8 9 // 3.發送異步請求 10 [request startAsynchronous]; 11 12 // ASI通過代理的方式處理異步請求,請求成功、失敗都會通知代理 13 // 代理需要遵守ASIHTTPRequestDelegate協議
ASIHTTPRequestDelegate
請求開始就調用
1 - (void)requestStarted:(ASIHTTPRequest *)request
接收到服務器的數據就調用
1 - (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data
請求成功完畢就調用
1 - (void)requestFinished:(ASIHTTPRequest *)request
請求失敗就調用
1 - (void)requestFailed:(ASIHTTPRequest *)request
注意:應當在控制器被銷毀的時候,取消請求
1 [request clearDelegatesAndCancel];
ASI的SEL回調
1 @property (atomic, assign) SEL didStartSelector; 2 @property (atomic, assign) SEL didReceiveResponseHeadersSelector; 3 @property (atomic, assign) SEL willRedirectSelector; 4 @property (atomic, assign) SEL didFinishSelector; 5 @property (atomic, assign) SEL didFailSelector; 6 @property (atomic, assign) SEL didReceiveDataSelector;
ASI的block回調
1 - (void)setStartedBlock:(ASIBasicBlock)aStartedBlock; 2 - (void)setHeadersReceivedBlock:(ASIHeadersBlock)aReceivedBlock; 3 - (void)setCompletionBlock:(ASIBasicBlock)aCompletionBlock; 4 - (void)setFailedBlock:(ASIBasicBlock)aFailedBlock; 5 - (void)setBytesReceivedBlock:(ASIProgressBlock)aBytesReceivedBlock; 6 - (void)setBytesSentBlock:(ASIProgressBlock)aBytesSentBlock; 7 - (void)setDownloadSizeIncrementedBlock:(ASISizeBlock) aDownloadSizeIncrementedBlock; 8 - (void)setUploadSizeIncrementedBlock:(ASISizeBlock) anUploadSizeIncrementedBlock; 9 - (void)setDataReceivedBlock:(ASIDataBlock)aReceivedBlock; 10 - (void)setAuthenticationNeededBlock:(ASIBasicBlock)anAuthenticationBlock; 11 - (void)setProxyAuthenticationNeededBlock:(ASIBasicBlock)aProxyAuthenticationBlock; 12 - (void)setRequestRedirectedBlock:(ASIBasicBlock)aRedirectBlock;
獲得服務器的響應
獲得狀態碼\狀態信息
1 @property (atomic, assign,readonly) int responseStatusCode; 2 @property (atomic, retain,readonly) NSString *responseStatusMessage;
獲得響應頭
1 @property (atomic, retain) NSDictionary *responseHeaders;
獲得實體內容(響應體)
1 - (NSData *)responseData; 2 - (NSString *)responseString;
發送普通的POST請求 – 方法1
1 // 創建請求 2 NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/MJServer/login"]; 3 ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 4 // 超時 5 request.timeOutSeconds = 5; 6 // 請求方法 7 request.requestMethod = @"POST"; 8 // 拼接請求體 9 NSData *data = [@"username=123&pwd=123" dataUsingEncoding:NSUTF8StringEncoding]; 10 [request appendPostData:data];
發送普通的POST請求 – 方法2
1 包含頭文件:#import "ASIFormDataRequest.h" 2 // 1.創建請求 3 NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/MJServer/login"]; 4 ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; 5 6 // 2.設置請求參數 7 [request addPostValue:@"123" forKey:@"username"]; 8 [request addPostValue:@"123" forKey:@"pwd"]; 9 // 注意addPostValue和setPostValue的區別
文件上傳
1 ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; 2 // 添加普通的請求參數 3 [request addPostValue:@"MJ" forKey:@"username"]; 4 // 添加文件參數 5 NSString *file = [[NSBundle mainBundle] pathForResource:@"musicplayer.png" ofType:nil]; 6 [request addFile:file forKey:@"file"]; 7 // 或者 8 UIImage *image = [UIImage imageNamed:@"musicplayer"]; 9 NSData *data = UIImagePNGRepresentation(image); 10 [request addData:data withFileName:@"test.png" andContentType:@"image/png" forKey:@"file"];
文件上傳 – 添加文件參數
1 有2種添加文件參數的方法 2 通過文件的全路徑 3 - (void)addFile:(NSString *)filePath forKey:(NSString *)key 4 - (void)addFile:(NSString *)filePath withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key 5 6 通過文件的具體數據 7 - (void)addData:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key
文件下載
1 // 設置緩存路徑 2 NSString *tmp = NSTemporaryDirectory(); 3 request.downloadDestinationPath = [tmp stringByAppendingPathComponent:@"tools.zip"]; 4 // 設置下載代理 5 request.downloadProgressDelegate = self.progressView; 6 7 大文件支持斷點續傳 8 [request setAllowResumeForFileDownloads:YES];
監聽文件上傳\下載進度
1 成為ASI的代理 2 - (void)setUploadProgressDelegate:(id)newDelegate 3 4 遵守ASIProgressDelegate協議,實現協議方法 5 - (void)setProgress:(float)newProgress;
緩存
ASI也提供了數據緩存功能
它只對Get請求的響應數據進行緩存
被緩存的數據必需是成功的200請求
使用ASIDownloadCache類管理緩存
1 常見ASIDownloadCache用法 2 取得默認的緩存對象 3 ASIDownloadCache *cache = [ASIDownloadCache sharedCache]; 4 5 設置緩存策略 6 - (void)setDefaultCachePolicy:(ASICachePolicy)cachePolicy 7 8 設置緩存路徑 9 - (void)setStoragePath:(NSString *)path
緩存策略 - ASICachePolicy
緩存策略:什么時候進行緩存,緩存數據的利用方式。可用組合使用
默認緩存策略:如果存在未過期的緩存數據,則使用緩存;否則進行網絡請求,判斷服務器版本與本地版本是否一樣,如果一樣,則使用緩存。如果服務器有新版本,會進行網絡請求,並更新本地緩存
ASIUseDefaultCachePolicy
ASIAskServerIfModifiedWhenStaleCachePolicy
與默認緩存大致一樣,區別僅是每次請求都會 去服務器判斷是否有更新
ASIAskServerIfModifiedCachePolicy
不讀取緩存數據
ASIDoNotReadFromCacheCachePolicy
不緩存數據,不寫緩存
ASIDoNotWriteToCacheCachePolicy
如果有緩存,不管其過期與否,總會拿來使用,沒有緩存就重新請求
ASIOnlyLoadIfNotCachedCachePolicy
有緩存,拿來使用,如果沒有緩存,請求將被取消(沒有錯誤信息)
ASIDontLoadCachePolicy
請求失敗時,如果有緩存則返回緩存(經常被用來與其它選項組合使用)
ASIFallbackToCacheIfLoadFailsCachePolicy
緩存某個請求
1 // 設置緩存策略 2 3 ASIDownloadCache *cache = [ASIDownloadCache sharedCache]; 4 5 [cache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy | ASIFallbackToCacheIfLoadFailsCachePolicy]; 6 7 // 使用緩存 8 9 [request setDownloadCache:cache]; 10 11 // 設置緩存的存儲策略(永久存儲) 12 13 [request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
ASIHTTPRequest緩存的存儲策略
緩存的存儲策略:緩存需要保存多長時間
默認策略,基於session的緩存數據存儲,當下次運行或[ASIHTTPRequest clearSession]時,緩存將失效(內存緩存)
ASICacheForSessionDurationCacheStoragePolicy
緩存數據永久保存在本地(硬盤緩存)
ASICachePermanentlyCacheStoragePolicy
緩存所有請求
1 // 設置緩存策略 2 ASIDownloadCache *cache = [ASIDownloadCache sharedCache]; 3 [cache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy | ASIFallbackToCacheIfLoadFailsCachePolicy]; 4 // 使用緩存 5 [ASIHTTPRequest setDefaultCache:cache];
緩存的其他特性
1 設置緩存的有效期 2 [request setSecondsToCache:60 * 60 * 24 * 7]; // 緩存7天 3 4 判斷數據是否從緩存讀取的 5 BOOL useCache = [request didUseCachedResponse];
ASIHTTPRequest
實際上ASIHTTPRequest繼承自NSOperation,意味着
可以將多個ASIHTTPRequest放到NSOperationQueue中,同時管理多個請求
可以設置請求之間的依賴
… …
ASIFormDataRequest繼承自ASIHTTPRequest
其他用法
現在是否有網絡請求在處理中
1 [ASIHTTPRequest isNetworkInUse];
當正在請求時,是否要在狀態欄顯示聯網狀態(轉圈圈)
1 [ASIHTTPRequest setShouldUpdateNetworkActivityIndicator:YES];
當應用后台運行時,是否仍然繼續處理網絡請求
1 request.shouldContinueWhenAppEntersBackground = YES;
設置請求超時后重試的次數
1 request.numberOfTimesToRetryOnTimeout = 2; // 重試2次