iOS网络请求框架AFNetworking和ASIHttpRequest实现原理

1:实现原理

ASI基于CFNetwork框架开发,而AFN基于NSURL.

ASI更加的底层,请求使用创建objcCFHTTPMessageRef进行,使用objcNSOperationQueue进行管理,objcASIHTTPRequest就是objcNSOpration的子类,并实现了NSCopy协议。使用objcstatic NSOperationQueue *sharedQueue, 在objcASIHTTPRequest执行网络请求时把自己加进去objcqueue

AFN基于NSURL,请求使用objcNSURLRequest作为参数传入objcNSURlconnection进行。使用objcNSOperationQueue进行管理,通过初始化objcAFHTTPRquestOperationManager进行多线程管理。

2:优缺点对比

ASI开发者已于2012年10月宣布暂停该开源库的更新.AFN的活跃维护者比较多。

AFN&ASI对比.png

2:ASI的大概实现

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;

}

然后在执行异步网络访问时,把自己扔进shareQueue进行管理。

- (void)startAsynchronous

{

#if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING

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

#endif

 [sharedQueue addOperation:self];

}

执行同步访问时更直接。注意[self main]. main方法里面执行了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]; //设置持久连接,重用request时用节约

[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]; //保持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]; //设置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.实现基本原理:

先看看AFHTTPRquestOperationManager的默认初始化方法:
可以看出默认的request为二进制,reponse为json解析。可以根据业务进行修改。

- (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的子类,并实现了NSURLConnectionDelegate等网络协议。
objc@interface AFURLConnectionOperation : NSOperation <NSURLConnectionDelegate, NSURLConnectionDataDelegate, NSSecureCoding, NSCopying>

是使用刚才manager初始化生成的operationQueue进行多线程管理,所以一个项目有一个manager然后用来管理网络请求就行了。多线程已经由AFN内部处理了。

- (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的生成,复用了很多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;

}

最后的回调,AFN是使用了NSOperation自己的block,难怪在协议找了好久没找到

- (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];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容