網路編程--ASI--(ASIHTTPRequest)介紹,c網路編程介紹
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次