iOS的ASIHTTPRequest學(xué)習(xí)
ASIHTTPRequest是一款極其強勁的HTTP訪問開源項目。讓簡單的API完成復(fù)雜的功能,
如:
異步請求,隊列請求,GZIP壓縮,緩存,斷點續(xù)傳,進度跟蹤,上傳文件,HTTP認證
在新的版本中,還加入了Objective-C閉包Block的支持,讓我們的代碼更加輕簡靈活。
下面就舉例說明它的API用法。
發(fā)起一個同步請求
同步意為著線程阻塞,在主線程中使用此方法會使應(yīng)用Hang住而不響應(yīng)任何用戶事件。所以,在應(yīng)用程序設(shè)計時,大多被用在專門的子線程增加用戶體驗,或用異步請求代替(下面會講到)。
- - (IBAction)grabURL:(id)sender
- {
- NSURL *url = [NSURL URLWithString:@" http://allseeing-i.com"];
- ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
- [request startSynchronous];
- NSError *error = [request error];
- if (!error) {
- NSString *response = [request responseString];
- }
- }
a, 用requestWithURL快捷方法獲取ASIHTTPRequest的一個實例
b, startSynchronous 方法啟動同步訪問,
c, 由于是同步請求,沒有基于事件的回調(diào)方法,所以從request的error屬性獲取錯誤信息。
d, responseString,為請求的返回NSString信息。
創(chuàng)建一個異步請求
異步請求的好處是不阻塞當(dāng)前線程,但相對于同步請求略為復(fù)雜,至少要添加兩個回調(diào)方法來獲取異步事件。
下面異步請求代碼完成上面同樣的一件事情:
- - (IBAction)grabURLInBackground:(id)sender
- {
- NSURL *url = [NSURL URLWithString:@" http://allseeing-i.com"];
- ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
- [request setDelegate:self];
- [request startAsynchronous];
- }
- - (void) requestFinished:(ASIHTTPRequest *)request
- {
- // Use when fetching text data
- NSString *responseString = [request responseString];
- // Use when fetching binary data
- NSData *responseData = [request responseData];
- }
- - (void)requestFailed:(ASIHTTPRequest *)request
- {
- NSError *error = [request error];
- }
a,與上面不同的地方是指定了一個 "delegate",并用startAsynchronous來啟動網(wǎng)絡(luò)請求。
b,在這里實現(xiàn)了兩個delegate的方法,當(dāng)數(shù)據(jù)請求成功時會調(diào)用requestFinished,請求失敗時(如網(wǎng)絡(luò)問題或服務(wù)器內(nèi)部錯誤)會調(diào)用requestFailed。
隊列請求
提供了一個對異步請求更加精準豐富的控制。
如,可以設(shè)置在隊列中,同步請求的連接數(shù)。往隊列里添加的請求實例數(shù)大于maxConcurrentOperationCount時,請求實例將被置為等待,直到前面至少有一個請求完成并出列才被放到隊列里執(zhí)行。
也適用于當(dāng)我們有多個請求需求按順序執(zhí)行的時候(可能是業(yè)務(wù)上的需要,也可能是軟件上的調(diào)優(yōu)),僅僅需要把maxConcurrentOperationCount設(shè)為“1”。
- - (IBAction)grabURLInTheBackground:(id)sender
- {
- if (![self queue]) {
- [self setQueue:[[[NSOperationQueue alloc] init] autorelease]];
- }
- NSURL *url = [NSURL URLWithString:@" http://allseeing-i.com"];
- ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
- [request setDelegate:self];
- [request setDidFinishSelector:@selector(requestDone:)];
- [request setDidFailSelector:@selector(requestWentWrong:)];
- [ [self queue] addOperation:request]; //queue is an NSOperationQueue
- }
- - (void)requestDone:(ASIHTTPRequest *)request
- {
- NSString *response = [request responseString];
- }
- - (void)requestWentWrong:(ASIHTTPRequest *)request
- {
- NSError *error = [request error];
- }
創(chuàng)建NSOperationQueue,這個Cocoa架構(gòu)的執(zhí)行任務(wù)(NSOperation)的任務(wù)隊列。我們通過 ASIHTTPRequest.h的源碼可以看到,此類本身就是一個NSOperation的子類。也就是說它可以直接被放到"任務(wù)隊列"中,并被執(zhí)行。 上面的代碼隊了隊列的創(chuàng)建與添加操作外,其它代碼與上一例一樣。
請求隊列上下文
a,可以設(shè)置一個上下文(userInfo)到request對象中,當(dāng)請求響應(yīng)完后可以通過訪問request對象的userInfo獲取里面的信息
b,為每一個請求實例設(shè)置不同的setDidFinishSelector / setDidFailSelector的回調(diào)方法
c,子類化ASIHTTPRequest,重寫requestFinished: 與 failWithProblem:方法
ASINetworkQueues, 它的delegate提供更為豐富的功能
提供的更多的回調(diào)方法如下:
a,requestDidStartSelector,請求發(fā)起時會調(diào)此方法,你可以在此方法中跟據(jù)業(yè)務(wù)選擇性的設(shè)置request對象的deleaget。
b,requestDidReceiveResponseHeadersSelector,當(dāng)接受完響應(yīng)的Header后設(shè)計此方法,這個對下載大數(shù)據(jù)的時候相當(dāng)有用,你可以在方法里做更多業(yè)務(wù)上的處理。
c,requestDidFinishSelector,請求并響應(yīng)成功完成時調(diào)用此方法
d,requestDidFailSelector,請求失敗
e,queueDidFinishSelector,整個隊列里的所有請求都結(jié)束時調(diào)用此方法。
它是NSOperationQueues的擴展,小而強大。但也與它的父類略有區(qū)別。如,僅添加到隊列中其實并不能執(zhí)行請求,只有調(diào)用[ queue g o]才會執(zhí)行;一個正在運行中的隊列,并不需要重復(fù)調(diào)用[ queue go ]。
默認情況下,隊列中的一個請求如果失敗,它會取消所有未完成的請求??梢栽O(shè)置[ queue setShouldCancelAllRequestsOnFailure:NO ]來修 正。 |
#p#
取消異步請求
首先,同步請求是不能取消的。
其次,不管是隊列請求,還是簡單的異步請求,全部調(diào)用[ request cancel ]來取消請求。
取消的請求默認都會按請求失敗處理,并調(diào)用請求失敗delegate。 如果不想調(diào)用delegate方法,則設(shè)置:[ request clearDelegatesAndCancel]; |
隊列請求中需要注意的是,如果你取消了一個請求,隊列會自動取消其它所有請求。
如果只想取消一個請求,可以設(shè)置隊列:[ queue setShouldCancelAllRequestsOnFailure:NO ];
如果想明確取消所有請求:[ queue cancelAllOperations ];
安全的內(nèi)存回收建議
request并沒有retain你的delegate,所以在沒有請求完的時候釋放了此delegate,需要在dealloc方法里先取消所有請求,再釋放請求實例,如:
- - (void)dealloc
- {
- [request clearDelegatesAndCancel];
- [request release];
- ...
- [super dealloc];
- }
向服務(wù)器端上傳數(shù)據(jù)
ASIFormDataRequest ,模擬 Form表單提交,其提交格式與 Header會自動識別。
沒有文件:application/x-www-form-urlencoded
有文件:multipart/form-data
- ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
- [request setPostValue:@"Ben" forKey:@"first_name"];
- [request setPostValue:@"Copsey" forKey:@"last_name"];
- [request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];
- [request addData:imageData withFileName:@"george.jpg" andContentType:@"image/jpeg"forKey:@"photos"];
如果要發(fā)送自定義數(shù)據(jù):
- ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
- [request appendPostData:[@"This is my data" dataUsingEncoding:NSUTF8StringEncoding]];
- // Default becomes POST when you use appendPostData: / appendPostDataFromFile: / setPostBody:
- [request setRequestMethod:@"PUT"];
- //用戶自定義數(shù)據(jù) 字典類型 (可選)
- request.userInfo = [NSDictionary dictionaryWithObject:method forKey:@"Method"];
- //post的數(shù)據(jù)
- [request appendPostData:[body dataUsingEncoding:NSUTF8StringEncoding]];
下載文件
通過設(shè)置request的setDownloadDestinationPath,可以設(shè)置下載文件用的下載目標目錄。
首先,下載過程文件會保存在temporaryFileDownloadPath目錄下。如果下載完成會做以下事情:
1,如果數(shù)據(jù)是壓縮的,進行解壓,并把文件放在downloadDestinationPath目錄中,臨時文件被刪除
2,如果下載失敗,臨時文件被直接移到downloadDestinationPath目錄,并替換同名文件。
如果你想獲取下載中的所有數(shù)據(jù),可以實現(xiàn)delegate中的request:didReceiveData:方法。但如果你實現(xiàn)了這個方法,request在下載完后,request并不把文件放在downloadDestinationPath中,需要手工處理。
獲取響應(yīng)信息
信息:status , header, responseEncoding
- [request responseStatusCode];
- [[request responseHeaders] objectForKey:@"X-Powered-By"];
- [request responseEncoding];
獲取請求進度
有兩個回調(diào)方法可以獲取請求進度,
1,downloadProgressDelegate,可以獲取下載進度
2,uploadProgressDelegate,可以獲取上傳進度
cookie的支持
如果Cookie存在的話,會把這些信息放在NSHTTPCookieStorage容器中共享,并供下次使用。
你可以用[ ASIHTTPRequest setSessionCookies:nil ] ; 清空所有Cookies。
當(dāng)然,你也可以取消默認的Cookie策略,而使自定義的Cookie:
- //Create a cookie
- NSDictionary *properties = [[[NSMutableDictionary alloc] init] autorelease];
- [properties setValue:[@"Test Value" encodedCookieValue] forKey:NSHTTPCookieValue];
- [properties setValue:@"ASIHTTPRequestTestCookie" forKey:NSHTTPCookieName];
- [properties setValue:@".allseeing-i.com" forKey:NSHTTPCookieDomain];
- [properties setValue:[NSDate dateWithTimeIntervalSinceNow:60*60] forKey:NSHTTPCookieExpires];
- [properties setValue:@"/asi-http-request/tests" forKey:NSHTTPCookiePath];
- NSHTTPCookie *cookie = [[[NSHTTPCookie alloc] initWithProperties:properties] autorelease];
- //This url will return the value of the 'ASIHTTPRequestTestCookie' cookie
- url = [NSURL URLWithString:@" http://allseeing-i.com/ASIHTTPRequest/tests/read_cookie"];
- request = [ASIHTTPRequest requestWithURL:url];
- [request setUseCookiePersistence:NO];
- [request setRequestCookies:[NSMutableArray arrayWithObject:cookie]];
- [request startSynchronous];
- //Should be: I have 'Test Value' as the value of 'ASIHTTPRequestTestCookie'
- NSLog(@"%@",[request responseString]);
#p#
大文件斷點續(xù)傳
0.94以后支持大文件的斷點下載,只需要設(shè)置:
- [ request setAllowResumeForFileDownloads:YES ];
- [ request setDownloadDestinationPath:downloadPath ];
就可以了。
ASIHTTPRequest會自動保存訪問過的URL信息,并備之后用。在以下幾個場景非常有用:
1,當(dāng)沒有網(wǎng)絡(luò)連接的時候。
2,已下載的數(shù)據(jù)再次請求時,僅當(dāng)它與本地版本不樣時才進行下載。
ASIDownloadCache 設(shè)置下載緩存
它對Get請求的響應(yīng)數(shù)據(jù)進行緩存(被緩存的數(shù)據(jù)必需是成功的200請求):
- [ASIHTTPRequest setDefaultCache:[ASIDownloadCache sharedCache]];
當(dāng)設(shè)置緩存策略后,所有的請求都被自動的緩存起來。
另外,如果僅僅希望某次請求使用緩存操作,也可以這樣使用:
- ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
- [request setDownloadCache:[ASIDownloadCache sharedCache]];
多種的緩存并存
僅僅需要創(chuàng)建不同的ASIDownloadCache,并設(shè)置緩存所使用的路徑,并設(shè)置到需要使用的request實例中:
- ASIDownloadCache *cache = [[[ASIDownloadCache alloc] init] autorelease];
- [cache setStoragePath:@"/Users/ben/Documents/Cached-Downloads"];
- [self setMyCache:cache];
- ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
- [request setDownloadCache:[self myCache]];
緩存策略
緩存策略是我們控制緩存行為的主要方式,如:什么時候進行緩存,緩存數(shù)據(jù)的利用方式。
以下是策略可選列表(可組合使用):
ASIUseDefaultCachePolicy
這是一個默認的緩存策略“ASIAskServerIfModifiedWhenStaleCachePolicy”,這個很明白,見名知意(它不能與其它策略組合使用)
ASIDoNotReadFromCacheCachePolicy
所讀數(shù)據(jù)不使用緩存
ASIDoNotWriteToCacheCachePolicy
不對緩存數(shù)據(jù)進行寫操作
ASIAskServerIfModifiedWhenStaleCachePolicy
默認緩存行為,request會先判斷是否存在緩存數(shù)據(jù)。a, 如果沒有再進行網(wǎng)絡(luò)請求。 b,如果存在緩存數(shù)據(jù),并且數(shù)據(jù)沒有過期,則使用緩存。c,如果存在緩存數(shù)據(jù),但已經(jīng)過期,request會先進行網(wǎng)絡(luò)請求,判斷服務(wù)器版本與本地版本是 否一樣,如果一樣,則使用緩存。如果服務(wù)器有新版本,會進行網(wǎng)絡(luò)請求,并更新本地緩存。
ASIAskServerIfModifiedCachePolicy
與默認緩存大致一樣,區(qū)別僅是每次請求都會 去服務(wù)器判斷是否有更新
ASIOnlyLoadIfNotCachedCachePolicy
如果有緩存在本地,不管其過期與否,總會拿來使用
ASIDontLoadCachePolicy
僅當(dāng)有緩存的時候才會被正確執(zhí)行,如果沒有緩存,request將被取消(沒有錯誤信息)
ASIFallbackToCacheIfLoadFailsCachePolicy
這個選項經(jīng)常被用來與其它選項組合使用。請求失敗時,如果有緩存當(dāng)網(wǎng)絡(luò)則返回本地緩存信息(這個在處理異常時非常有用)
如果設(shè)置了“defaultCachePolicy”則所有的請求都會使用此緩存。
緩存存儲方式
你可以設(shè)置緩存的數(shù)據(jù)需要保存多長時間,ASIHTTPRequest提供了兩種策略:
a,ASICacheForSessionDurationCacheStoragePolicy,默認策略,基于session的緩存數(shù)據(jù)存儲。當(dāng)下次運行或[ASIHTTPRequest clearSession]時,緩存將失效。
b,ASICachePermanentlyCacheStoragePolicy,把緩存數(shù)據(jù)***保存在本地,
如:
- ASIHTTPRequest *request = [ ASIHTTPRequest requestWithURL:url ];
- [ request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy ];
另外,也可以使用clearCachedResponsesForStoragePolicy來清空指定策略下的緩存數(shù)據(jù)。
緩存其它特性
設(shè)置是否按服務(wù)器在Header里指定的是否可被緩存或過期策略進行緩存:
- [[ ASIDownloadCache sharedCache ] setShouldRespectCacheControlHeaders:NO ];
設(shè)置request緩存的有效時間:
- [ request setSecondsToCache:60*60*24*30 ]; // 緩存30天
可以判斷數(shù)據(jù)是否從緩存讀?。?/p>
- [ request didUseCachedResponse ];
設(shè)置緩存所使用的路徑:
- [ request setDownloadDestinationPath:[[ ASIDownloadCache sharedCache ] pathToStoreCachedResponseDataForRequest:request ]];
實現(xiàn)自定義的緩存
只要簡單的實現(xiàn)ASICacheDelegate接口就可以被用來使用。
使用代理請求
默認的情況下,ASIHTTPRequest會使用被設(shè)置的默認代理。但你也可以手動修改http代理:
- // Configure a proxy server manually
- NSURL *url = [ NSURL URLWithString:@" http://allseeing-i.com/ignore" ];
- ASIHTTPRequest *request = [ ASIHTTPRequest requestWithURL:url ];
- [ request setProxyHost:@"192.168.0.1" ];
- [ request setProxyPort:3128 ];
- // Alternatively, you can use a manually-specified Proxy Auto Config file (PAC)
- // (It's probably best if you use a local file)
- [request setPACurl:[NSURL URLWithString:@"file:///Users/ben/Desktop/test.pac"]];
ASIHTTPRequest, 請求的其它特性
iOS4中,當(dāng)應(yīng)用后臺運行時仍然請求數(shù)據(jù):
- [ request setShouldContinueWhenAppEntersBackground:YES ];
是否有網(wǎng)絡(luò)請求:
- [ ASIHTTPRequest isNetworkInUse ]
是否顯示網(wǎng)絡(luò)請求信息在status bar上:
- [ ASIHTTPRequest setShouldUpdateNetworkActivityIndicator:NO ];
設(shè)置請求超時時,設(shè)置重試的次數(shù):
- [ request setNumberOfTimesToRetryOnTimeout:2 ];
KeepAlive的支持:
- // Set the amount of time to hang on to a persistent connection before it should expire to 2 minutes
- [ request setPersistentConnectionTimeoutSeconds:120 ];
- // Disable persistent connections entirely
- [ request setShouldAttemptPersistentConnection:NO ];






