iOS網(wǎng)絡(luò)請求框架AFNetworking和ASIHttpRequest實現(xiàn)原理

1:實現(xiàn)原理

ASI基于CFNetwork框架開發(fā)悬嗓,而AFN基于NSURL.

ASI更加的底層丈攒,請求使用創(chuàng)建objcCFHTTPMessageRef進行圆丹,使用objcNSOperationQueue進行管理墓捻,objcASIHTTPRequest就是objcNSOpration的子類谜叹,并實現(xiàn)了NSCopy協(xié)議右锨。使用objcstatic NSOperationQueue *sharedQueue括堤, 在objcASIHTTPRequest執(zhí)行網(wǎng)絡(luò)請求時把自己加進去objcqueue

AFN基于NSURL绍移,請求使用objcNSURLRequest作為參數(shù)傳入objcNSURlconnection進行悄窃。使用objcNSOperationQueue進行管理,通過初始化objcAFHTTPRquestOperationManager進行多線程管理蹂窖。

2:優(yōu)缺點對比

ASI開發(fā)者已于2012年10月宣布暫停該開源庫的更新.AFN的活躍維護者比較多广匙。

AFN&ASI對比.png

2:ASI的大概實現(xiàn)

ASIHTTPRequest是NSOperation的子類。 在ASIHTTPRequest有個初始方法:

- (id)initWithURL:(NSURL *)newURL

{

 self = [self init];

 [self setRequestMethod:@"GET"];

 [self setRunLoopMode:NSDefaultRunLoopMode];

 [self setShouldAttemptPersistentConnection:YES];

 [self setPersistentConnectionTimeoutSeconds:60.0];

 [self setShouldPresentCredentialsBeforeChallenge:YES];

 [self setShouldRedirect:YES];

 [self setShowAccurateProgress:YES];

 [self setShouldResetDownloadProgress:YES];

 [self setShouldResetUploadProgress:YES];

 [self setAllowCompressedResponse:YES];

 [self setShouldWaitToInflateCompressedResponses:YES];

 [self setDefaultResponseEncoding:NSISOLatin1StringEncoding];

 [self setShouldPresentProxyAuthenticationDialog:YES];

 [self setTimeOutSeconds:[ASIHTTPRequest defaultTimeOutSeconds]];

 [self setUseSessionPersistence:YES];

 [self setUseCookiePersistence:YES];

 [self setValidatesSecureCertificate:YES];

 [self setRequestCookies:[[[NSMutableArray alloc] init] autorelease]];

 [self setDidStartSelector:@selector(requestStarted:)];

 [self setDidReceiveResponseHeadersSelector:@selector(request:didReceiveResponseHeaders:)];

 [self setWillRedirectSelector:@selector(request:willRedirectToURL:)];

 [self setDidFinishSelector:@selector(requestFinished:)];

 [self setDidFailSelector:@selector(requestFailed:)];

 [self setDidReceiveDataSelector:@selector(request:didReceiveData:)];

 [self setURL:newURL];

 [self setCancelledLock:[[[NSRecursiveLock alloc] init] autorelease]];

 [self setDownloadCache:[[self class] defaultCache]];

 return self;

}

然后在執(zhí)行異步網(wǎng)絡(luò)訪問時恼策,把自己扔進shareQueue進行管理鸦致。

- (void)startAsynchronous

{

#if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING

 ASI_DEBUG_LOG(@"[STATUS] Starting asynchronous request %@",self);

#endif

 [sharedQueue addOperation:self];

}

執(zhí)行同步訪問時更直接。注意[self main]. main方法里面執(zhí)行了CFNetwork的操作涣楷。
- (void)startSynchronous

{

#if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING

 ASI_DEBUG_LOG(@"[STATUS] Starting synchronous request %@",self);

#endif

 [self setSynchronous:YES];

 [self setRunLoopMode:ASIHTTPRequestRunLoopMode];

 [self setInProgress:YES];

 if (![self isCancelled] && ![self complete]) {

 [self main];

 while (!complete) {

 [[NSRunLoop currentRunLoop] runMode:[self runLoopMode] beforeDate:[NSDate distantFuture]];

 }

 }

 [self setInProgress:NO];

}

[](http://mozhenhau.com/2015/08/12/IOS%E7%BD%91%E7%BB%9C%E8%AF%B7%E6%B1%82%E6%A1%86%E6%9E%B6AFNetworking%E5%92%8CASIHttpRequest%E5%AF%B9%E6%AF%94/#2-ASI_u57FA_u672C_u4F7F_u7528)2.ASI基本使用
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"XXXXX"]];

[request setDelegate:self]; //ASIHTTPRequestDelegate

[request startAsynchronous];

不用進行很多配置分唾,是因為ASIHTTPRequest的requestWithURL方法有默認配置,可以在實例化后自己再修改狮斗。如下(還有更多的自己閱讀源碼):
[self setRequestMethod:@"GET"]; //訪問方法

[self setRunLoopMode:NSDefaultRunLoopMode]; //默認runloop

[self setShouldAttemptPersistentConnection:YES]; //設(shè)置持久連接,重用request時用節(jié)約

[self setPersistentConnectionTimeoutSeconds:60.0];

[self setShouldPresentCredentialsBeforeChallenge:YES]; //是否要證書驗證

[self setShouldRedirect:YES];

[self setShowAccurateProgress:YES]; //進度

[self setShouldResetDownloadProgress:YES];

[self setShouldResetUploadProgress:YES];

[self setAllowCompressedResponse:YES];

[self setShouldWaitToInflateCompressedResponses:YES];

[self setDefaultResponseEncoding:NSISOLatin1StringEncoding];

[self setShouldPresentProxyAuthenticationDialog:YES];

[self setTimeOutSeconds:[ASIHTTPRequest defaultTimeOutSeconds]]; //請求的網(wǎng)絡(luò)等待時長

[self setUseSessionPersistence:YES]; //保持session

[self setUseCookiePersistence:YES]; //保持cookie

[self setValidatesSecureCertificate:YES];

[self setRequestCookies:[[[NSMutableArray alloc] init] autorelease]];

[self setDidStartSelector:@selector(requestStarted:)]; //請求開始

[self setDidReceiveResponseHeadersSelector:@selector(request:didReceiveResponseHeaders:)]; //獲取到ResponseHeader

[self setWillRedirectSelector:@selector(request:willRedirectToURL:)];

[self setDidFinishSelector:@selector(requestFinished:)]; //請求完成

[self setDidFailSelector:@selector(requestFailed:)]; //請求失敗

[self setDidReceiveDataSelector:@selector(request:didReceiveData:)]; //獲取到data绽乔,多次

[self setURL:newURL]; //設(shè)置URL

[self setCancelledLock:[[[NSRecursiveLock alloc] init] autorelease]];

[self setDownloadCache:[[self class] defaultCache]];

ASIHTTPRequestDelegate的代理:

- (void)requestStarted:(ASIHTTPRequest *)request;

- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders;

- (void)request:(ASIHTTPRequest *)request willRedirectToURL:(NSURL *)newURL;

- (void)requestFinished:(ASIHTTPRequest *)request;

- (void)requestFailed:(ASIHTTPRequest *)request;

- (void)requestRedirected:(ASIHTTPRequest *)request;

- (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data;

- (void)authenticationNeededForRequest:(ASIHTTPRequest *)request;

- (void)proxyAuthenticationNeededForRequest:(ASIHTTPRequest *)request;

2.AFN基本使用

1.實現(xiàn)基本原理:

先看看AFHTTPRquestOperationManager的默認初始化方法:
可以看出默認的request為二進制,reponse為json解析碳褒≌墼遥可以根據(jù)業(yè)務(wù)進行修改看疗。

- (instancetype)initWithBaseURL:(NSURL *)url {

 self = [super init];

 if (!self) {

 return nil;

 }

 // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected

 if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {

 url = [url URLByAppendingPathComponent:@""];

 }

 self.baseURL = url; //初始化了baseurl,比如你的訪問地址是http://192.168.0.100/login.action . 初始化baseUrl為http://192.168.0.100/ , 以后manager GET:@"login.action"即可睦授。

 self.requestSerializer = [AFHTTPRequestSerializer serializer];

 self.responseSerializer = [AFJSONResponseSerializer serializer];

 self.securityPolicy = [AFSecurityPolicy defaultPolicy]; //AFSSLPinningModeNone無隱私要求

 self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];

 self.operationQueue = [[NSOperationQueue alloc] init];

 self.shouldUseCredentialStorage = YES;

 return self;

}

再看看其中一個方法GET方法两芳。
AFHTTPRequestOperation 是 AFURLConnectionOperation的子類,AFURLConnectionOperation的子類是NSOperation的子類去枷,并實現(xiàn)了NSURLConnectionDelegate等網(wǎng)絡(luò)協(xié)議怖辆。
objc@interface AFURLConnectionOperation : NSOperation <NSURLConnectionDelegate, NSURLConnectionDataDelegate, NSSecureCoding, NSCopying>

是使用剛才manager初始化生成的operationQueue進行多線程管理,所以一個項目有一個manager然后用來管理網(wǎng)絡(luò)請求就行了删顶。多線程已經(jīng)由AFN內(nèi)部處理了竖螃。

- (AFHTTPRequestOperation *)GET:(NSString *)URLString

 parameters:(id)parameters

 success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

 failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

{

 AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"GET" URLString:URLString parameters:parameters success:success failure:failure];

 [self.operationQueue addOperation:operation];

 return operation;

}

AFHTTPRequestOperation的生成,復(fù)用了很多manager的屬性:

- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request

 success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

 failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

{

 AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

 operation.responseSerializer = self.responseSerializer;

 operation.shouldUseCredentialStorage = self.shouldUseCredentialStorage;

 operation.credential = self.credential;

 operation.securityPolicy = self.securityPolicy;

 [operation setCompletionBlockWithSuccess:success failure:failure]; //注意這個地方

 operation.completionQueue = self.completionQueue;

 operation.completionGroup = self.completionGroup;

 return operation;

}

最后的回調(diào)逗余,AFN是使用了NSOperation自己的block特咆,難怪在協(xié)議找了好久沒找到

- (void)setCompletionBlock:(void (^)(void))block {

 [self.lock lock];

 if (!block) {

 [super setCompletionBlock:nil];

 } else {

 __weak __typeof(self)weakSelf = self;

 [super setCompletionBlock:^ {

 __strong __typeof(weakSelf)strongSelf = weakSelf;

#pragma clang diagnostic push

#pragma clang diagnostic ignored "-Wgnu"

 dispatch_group_t group = strongSelf.completionGroup ?: url_request_operation_completion_group();

 dispatch_queue_t queue = strongSelf.completionQueue ?: dispatch_get_main_queue();

#pragma clang diagnostic pop

 dispatch_group_async(group, queue, ^{

 block();

 });

 dispatch_group_notify(group, url_request_operation_completion_queue(), ^{

 [strongSelf setCompletionBlock:nil];

 });

 }];

 }

 [self.lock unlock];

}

2.基本GET

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

 [manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

 NSLog(@"JSON: %@", responseObject);

 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

 NSLog(@"Error: %@", error);

 }];

3.下載一個文件

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];

NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {

 NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];

 return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];

} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {

 NSLog(@"File downloaded to: %@", filePath);

}];

[downloadTask resume];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市录粱,隨后出現(xiàn)的幾起案子腻格,更是在濱河造成了極大的恐慌,老刑警劉巖关摇,帶你破解...
    沈念sama閱讀 216,496評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件荒叶,死亡現(xiàn)場離奇詭異,居然都是意外死亡输虱,警方通過查閱死者的電腦和手機些楣,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來宪睹,“玉大人愁茁,你說我怎么就攤上這事⊥げ。” “怎么了鹅很?”我有些...
    開封第一講書人閱讀 162,632評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長罪帖。 經(jīng)常有香客問我促煮,道長,這世上最難降的妖魔是什么整袁? 我笑而不...
    開封第一講書人閱讀 58,180評論 1 292
  • 正文 為了忘掉前任菠齿,我火速辦了婚禮,結(jié)果婚禮上坐昙,老公的妹妹穿的比我還像新娘绳匀。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 67,198評論 6 388
  • 文/花漫 我一把揭開白布疾棵。 她就那樣靜靜地躺著戈钢,像睡著了一般。 火紅的嫁衣襯著肌膚如雪是尔。 梳的紋絲不亂的頭發(fā)上殉了,一...
    開封第一講書人閱讀 51,165評論 1 299
  • 那天,我揣著相機與錄音嗜历,去河邊找鬼宣渗。 笑死抖所,一個胖子當著我的面吹牛梨州,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播田轧,決...
    沈念sama閱讀 40,052評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼暴匠,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了傻粘?” 一聲冷哼從身側(cè)響起每窖,我...
    開封第一講書人閱讀 38,910評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎弦悉,沒想到半個月后窒典,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,324評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡稽莉,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,542評論 2 332
  • 正文 我和宋清朗相戀三年瀑志,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片污秆。...
    茶點故事閱讀 39,711評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡劈猪,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出良拼,到底是詐尸還是另有隱情战得,我是刑警寧澤,帶...
    沈念sama閱讀 35,424評論 5 343
  • 正文 年R本政府宣布庸推,位于F島的核電站常侦,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏贬媒。R本人自食惡果不足惜聋亡,卻給世界環(huán)境...
    茶點故事閱讀 41,017評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望掖蛤。 院中可真熱鬧杀捻,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至垢袱,卻和暖如春墓拜,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背请契。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評論 1 269
  • 我被黑心中介騙來泰國打工咳榜, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人爽锥。 一個月前我還...
    沈念sama閱讀 47,722評論 2 368
  • 正文 我出身青樓涌韩,卻偏偏與公主長得像,于是被迫代替她去往敵國和親氯夷。 傳聞我的和親對象是個殘疾皇子臣樱,可洞房花燭夜當晚...
    茶點故事閱讀 44,611評論 2 353

推薦閱讀更多精彩內(nèi)容