iPhone应用开发中ASIHTTPRequest详解

移动开发 iOS
本文介绍的是iPhone应用开发中ASIHTTPRequest,ASIHTTPRequest 是一款极其强劲的 HTTP 访问开源项目。让简单的 API 完成复杂的功能,

iPhone应用开发中ASIHTTPRequest详解是本文要讲解的内容,ASIHTTPRequest 是一款极其强劲的 HTTP 访问开源项目。让简单的 API 完成复杂的功能,如:异步请求,队列请求,GZIP 压缩,缓存,断点续传,进度跟踪,上传文件,HTTP 认证。在新的版本中,还加入了 Objective-C 闭包 Block 的支持,让我们的代码加轻简灵活。

下面就举例说明它的 API 用法。

发起一个同步请求

同步意为着线程阻塞,在主线程中使用此方法会使应用Hang住而不响应任何用户事件。所以,在应用程序设计时,大多被用在专门的子线程增加用户体验,或用异步请求代替(下面会讲到)。

  1. - (IBAction)grabURL:(id)sender  
  2.  {  
  3.    NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];  
  4.    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];  
  5.    [request startSynchronous];  
  6.    NSError *error = [request error];  
  7.    if (!error) {  
  8.      NSString *response = [request responseString];  
  9.    }  
  10.  } 

用 requestWithURL 快捷方法获取 ASIHTTPRequest 的一个实例

startSynchronous 方法启动同步访问

由于是同步请求,没有基于事件的回调方法,所以从 request的error 属性获取错误信息

responseString,为请求的返回 NSString 信息

创建一个异步请求

异步请求的好处是不阻塞当前线程,但相对于同步请求略为复杂,至少要添加两个回调方法来获取异步事件。下面异步请求代码完成上面同样的一件事情:

  1. - (IBAction)grabURLInBackground:(id)sender  
  2. {  
  3.    NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];  
  4.    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];  
  5.    [request setDelegate:self];  
  6.    [request startAsynchronous];  
  7. }  
  8. - (void)requestFinished:(ASIHTTPRequest *)request  
  9. {  
  10.    // Use when fetching text data  
  11.    NSString *responseString = [request responseString];  
  12.    // Use when fetching binary data  
  13.    NSData *responseData = [request responseData];  
  14. }  
  15. - (void)requestFailed:(ASIHTTPRequest *)request  
  16. {  
  17.    NSError *error = [request error];  

与上面不同的地方是指定了一个 "delegate",并用 startAsynchronous 来启动网络请求

在这里实现了两个 delegate 的方法,当数据请求成功时会调用 requestFinished,请求失败时(如网络问题或服务器内部错误)会调用 requestFailed。

队列请求

提供了一个对异步请求更加精准丰富的控制。如:可以设置在队列中同步请求的连接数。往队列里添加的请求实例数大于 maxConcurrentOperationCount 时,请求实例将被置为等待,直到前面至少有一个请求完成并出列才被放到队列里执行。这也适用于当我们有多个请求需求按顺序执行的时候(可能是业务上的需要,也可能是软件上的调优),仅仅需要把 maxConcurrentOperationCount 设为“1”。

  1. - (IBAction)grabURLInTheBackground:(id)sender  
  2. {  
  3.    if (![self queue]) {  
  4.       [self setQueue:[[[NSOperationQueue alloc] init] autorelease]];  
  5.    }  
  6.    NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];  
  7.    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];  
  8.    [request setDelegate:self];  
  9.    [request setDidFinishSelector:@selector(requestDone:)];  
  10.    [request setDidFailSelector:@selector(requestWentWrong:)];  
  11.    [[self queue] addOperation:request]; //queue is an NSOperationQueue  
  12. }  
  13. - (void)requestDone:(ASIHTTPRequest *)request  
  14. {  
  15.    NSString *response = [request responseString];  
  16. }  
  17. - (void)requestWentWrong:(ASIHTTPRequest *)request  
  18. {  
  19.    NSError *error = [request error];  

创建 NSOperationQueue,这个 Cocoa 架构的执行任务(NSOperation)的任务队列。我们通过 ASIHTTPRequest.h 的源码可以看到,此类本身就是一个 NSOperation 的子类。也就是说它可以直接被放到"任务队列"中并被执行。上面的代码除了队列的创建与添加操作外,其它代码与上一例一样。

队列异步请求中中获取或识别不同request小技巧

可以设置一个上下文(userInfo)到 request 对象中,当请求响应完后可以通过访问 request 对象的 userInfo 获取里面的信息

为每一个请求实例设置不同的 setDidFinishSelector / setDidFailSelector 的回调方法

子类化 ASIHTTPRequest,重写 requestFinished: 与 failWithProblem: 方法

ASINetworkQueues, 它的delegate提供更为丰富的功能

提供的更多的回调方法如下:

  1. requestDidStartSelector,请求发起时会调此方法,你可以在此方法中跟据业务选择性的设置 request 对象的 deleaget   
  2. requestDidReceiveResponseHeadersSelector,当接受完响应的 Header 后设计此方法,这个对下载大数据的时候相当有用,你可以在方法里做更多业务上的处理   
  3. requestDidFinishSelector,请求并响应成功完成时调用此方法   
  4. requestDidFailSelector,请求失败   
  5. queueDidFinishSelector,整个队列里的所有请求都结束时调用此方法  

它是 NSOperationQueues 的扩展,小而强大。但也与它的父类略有区别。如,仅添加到队列中其实并不能执行请求,只有调用[  queue g o ]才会执行;一个正在运行中的队列,并不需要重复调用[  queue go  ]。默认情况下,队列中的一个请求如果失败,它会取消所有未完成的请求。可以设置[  queue setShouldCancelAllRequestsOnFailure:NO  ]来修正。

取消异步请求

首先,同步请求是不能取消的。

其次,不管是队列请求,还是简单的异步请求,全部调用[ request cancel ]来取消请求。取消的请求默认都会按请求失败处理,并调用请求失败delegate。

如果不想调用delegate方法,则设置:[ request clearDelegatesAndCancel];

队列请求中需要注意的是,如果你取消了一个请求,队列会自动取消其它所有请求。如果只想取消一个请求,可以设置队列:

  1. [ queue setShouldCancelAllRequestsOnFailure:NO ];  

如果想明确取消所有请求:[ queue cancelAllOperations ];

安全的内存回收建议

request并没有retain你的delegate,所以在没有请求完的时候释放了此delegate,需要在dealloc方法里先取消所有请求,再释放请求实例,如:

  1.  - (void)dealloc  
  2. {  
  3.    [request clearDelegatesAndCancel];  
  4.    [request release];  
  5.    ...  
  6.    [super dealloc];  

向服务器端上传数据

ASIFormDataRequest ,模拟 Form 表单提交,其提交格式与 Header 会自动识别。

没有文件:application/x-www-form-urlencoded

有文件:multipart/form-data

  1.  ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];  
  2. [request setPostValue:@"Ben" forKey:@"first_name"];  
  3. [request setPostValue:@"Copsey" forKey:@"last_name"];  
  4. [request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];  
  5. [request addData:imageData withFileName:@"george.jpg" andContentType:@"image/jpeg" forKey:@"photos"]; 

如果要发送自定义数据:

  1. ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];  
  2. [request appendPostData:[@"This is my data" dataUsingEncoding:NSUTF8StringEncoding]];  
  3. // Default becomes POST when you use appendPostData: / appendPostDataFromFile: / setPostBody:  
  4. [request setRequestMethod:@"PUT"]; 

下载文件

通过设置request的setDownloadDestinationPath,可以设置下载文件用的下载目标目录。

首先,下载过程文件会保存在temporaryFileDownloadPath目录下。如果下载完成会做以下事情:

如果数据是压缩的,进行解压,并把文件放在 downloadDestinationPath 目录中,临时文件被删除
如果下载失败,临时文件被直接移到 downloadDestinationPath 目录,并替换同名文件

如果你想获取下载中的所有数据,可以实现 delegate 中的 request:didReceiveData:方法。但如果你实现了这个方法,request 在下载完后,request 并不把文件放在 downloadDestinationPath 中,需要手工处理。

获取响应信息

信息:status , header, responseEncoding

  1. [request responseStatusCode];  
  2. [[request responseHeaders] objectForKey:@"X-Powered-By"];  
  3. [request responseEncoding]; 

获取请求进度

有两个回调方法可以获取请求进度:

  1. downloadProgressDelegate,可以获取下载进度   
  2. uploadProgressDelegate,可以获取上传进度  

cookie的支持

如果 Cookie 存在的话,会把这些信息放在 NSHTTPCookieStorage 容器中共享,并供下次使用。你可以用 [ ASIHTTPRequest setSessionCookies:nil ] ; 清空所有 Cookies。当然,你也可以取消默认的Cookie策略,而使自定义的Cookie:

  1. //Create a cookie  
  2. NSDictionary *properties = [[[NSMutableDictionary alloc] init] autorelease];  
  3. [properties setValue:[@"Test Value" encodedCookieValue] forKey:NSHTTPCookieValue];  
  4. [properties setValue:@"ASIHTTPRequestTestCookie" forKey:NSHTTPCookieName];  
  5. [properties setValue:@".allseeing-i.com" forKey:NSHTTPCookieDomain];  
  6. [properties setValue:[NSDate dateWithTimeIntervalSinceNow:60*60] forKey:NSHTTPCookieExpires];  
  7. [properties setValue:@"/asi-http-request/tests" forKey:NSHTTPCookiePath];  
  8. NSHTTPCookie *cookie = [[[NSHTTPCookie alloc] initWithProperties:properties] autorelease];  
  9.  
  10. //This url will return the value of the 'ASIHTTPRequestTestCookie' cookie  
  11. url = [NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/read_cookie"];  
  12. request = [ASIHTTPRequest requestWithURL:url];  
  13. [request setUseCookiePersistence:NO];  
  14. [request setRequestCookies:[NSMutableArray arrayWithObject:cookie]];  
  15. [request startSynchronous];  
  16.  
  17. //Should be: I have 'Test Value' as the value of 'ASIHTTPRequestTestCookie'  
  18. NSLog(@"%@",[request responseString]); 

大文件断点续传0.94 以后支持大文件的断点下载,只需要设置

  1. [ request setAllowResumeForFileDownloads:YES ];  
  2. [ request setDownloadDestinationPath:downloadPath ]; 

就可以了。

小结:iPhone应用开发中ASIHTTPRequest详解的内容介绍完了,希望通过本文的学习能对你有所帮助!

责任编辑:zhaolei 来源: 互联网
相关推荐

2011-08-11 13:35:28

iPhoneASIHTTPRequHTTP

2011-08-12 13:35:23

iPhone文件流ASIHTTPRequ

2011-08-12 14:33:06

iPhone缓存文件

2011-08-15 11:37:20

iPhone开发Mask

2011-08-17 15:10:21

iPhone开发Web视图

2011-08-22 10:06:38

IOS开发ASIHTTPRequHTTP 请求

2011-08-02 17:27:06

iPhone应用 剪切技巧

2011-07-27 11:14:37

iPhone UITableVie

2011-08-17 15:19:38

iPhone应用数据

2011-08-12 10:04:24

iPhone开发视图

2011-07-26 09:41:23

iPhone xcode Mac OS X

2013-07-22 13:48:55

iOS开发ASIHTTPRequ使用Cookie

2011-08-09 14:08:51

iPhoneHTTP请求协议

2011-08-03 17:18:58

iPhone UILabel UISlider

2011-08-15 15:44:46

iPhone开发PDF

2011-08-09 17:12:30

iPhoneCFRunLoop

2011-08-18 16:24:44

iPhone开发图片

2011-08-22 14:12:48

iPhone开发NSTableView

2011-07-27 10:16:41

iPhone SQLite 数据库

2011-08-12 14:04:53

iPhone动画
点赞
收藏

51CTO技术栈公众号