iOS開發 - HTTP終結者 "ASI"

來源:互聯網
上載者:User

標籤:ios   asi   http終結者   http   

ASI

全稱是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

發送同步請求
 #import "ASIHTTPRequest.h"// 1.建立請求NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/Server/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]
發送非同步請求
// 1.建立請求NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/MJServer/login?username=123&pwd=123"];ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];request.timeOutSeconds = 5; // 逾時// 2.設定代理request.delegate = self;// 3.發送非同步請求[request startAsynchronous];// ASI通過代理的方式處理非同步請求,請求成功、失敗都會通知代理//   代理需要遵守ASIHTTPRequestDelegate協議
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/Server/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種添加檔案參數的方法//通過檔案的全路徑- (void)addFile:(NSString *)filePath forKey:(NSString *)key- (void)addFile:(NSString *)filePath withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key//通過檔案的具體資料- (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

緩衝策略:什麼時候進行緩衝,快取資料的利用方式。可用組合使用
預設緩衝策略:如果存在未到期的快取資料,則使用緩衝;否則進行網路請求,判斷伺服器版本與本地版本是否一樣,如果一樣,則使用緩衝。如果伺服器有新版本,會進行網路請求,並更

//新本機快取ASIUseDefaultCachePolicyASIAskServerIfModifiedWhenStaleCachePolicy//與預設緩衝大致一樣,區別僅是每次請求都會 去伺服器判斷是否有更新ASIAskServerIfModifiedCachePolicy不讀取快取資料//ASIDoNotReadFromCacheCachePolicy//不快取資料,不寫緩衝ASIDoNotWriteToCacheCachePolicy//如果有緩衝,不管其到期與否,總會拿來使用,沒有緩衝就重新請求ASIOnlyLoadIfNotCachedCachePolicy//有緩衝,拿來使用,如果沒有緩衝,請求將被取消(沒有錯誤資訊)ASIDontLoadCachePolicy//請求失敗時,如果有緩衝則返回緩衝(經常被用來與其它選項組合使用)ASIFallbackToCacheIfLoadFailsCachePolicy
緩衝某個請求
// 設定緩衝策略ASIDownloadCache *cache = [ASIDownloadCache sharedCache];[cache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy | ASIFallbackToCacheIfLoadFailsCachePolicy];// 使用緩衝[request setDownloadCache:cache];// 設定緩衝的儲存策略(永久儲存)[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];// 設定緩衝策略ASIDownloadCache *cache = [ASIDownloadCache sharedCache];[cache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy | ASIFallbackToCacheIfLoadFailsCachePolicy];// 使用緩衝[ASIHTTPRequest setDefaultCache:cache];
其他用法
現在是否有網路請求在處理中[ASIHTTPRequest isNetworkInUse];當正在請求時,是否要在狀態列顯示連網狀態(轉圈圈)[ASIHTTPRequest setShouldUpdateNetworkActivityIndicator:YES];當應用後台運行時,是否仍然繼續處理網路請求request.shouldContinueWhenAppEntersBackground = YES;佈建要求逾時後重試的次數request.numberOfTimesToRetryOnTimeout = 2; // 重試2次

iOS開發 - HTTP終結者 "ASI"

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.