ASIHttpRequest可以让简单的API完成复杂的功能,如:异步请求,队列请求,GZIP压缩,缓存,断点续传,进度跟踪,上传文件,HTTP认证。新版本还支持Block
简单用法:
1.发起一个同步请求:主线程中会使程序出现假死现象,所以一般用子线程或者异步请求
- (void)startSynch
{
NSURL *url = [NSURL URLWithString:@"http://www.testURL.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
}
}
1)用requestWithURL快捷方法获取ASIHttpRequest的一个实例
2)startSynchronous方法启动同步访问
3)由于同步请求,没有基于时间的回调方法,所以从request的error属性获取错误信息
4)responseString,为请求返回NSString信息
2.创建一个异步请求:异步请求的好处是不阻塞线程,但对于同步请求略为复杂,至少要添加两个回调方法来获取异步事件。异步事件请求代码完成上面同步代码完成的事情
- (void)startAsynch
{
NSURL *url = [NSURL URLWithString:@"http://www.testURL.com"];
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSString *responseString = [request responseString];
NSData *responseData = [request responseData];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
}
队列请求:提供一个对异步请求更加精准丰富的控制,例:可以在队列中同步请求的连接数。往队列里添加的请求实例数大于maxConcurrentOperationCount时,请求实例将被置为等待,直到前面至少有一个请求完成并出列才被放到队列里执行。这也适用于当我们有多个请求需求按顺序执行的时候,仅仅需要把maxConcurrentOperationCount设为1.
- (void)setQueue
{
if (![self queue]) {
[self setQueue:[[NSOperationQueue alloc] init]];
}
NSURL *url = [NSURL URLWithString:@"http://www.testURL.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setDidFinishSelector:@selector(requestDone:)];
[request setDidFailSelector:@selector(requestFail:)];
[self.queue addOperation:request];
}
- (void)requestDone:(ASIHTTPRequest *)request
{
NSString *response = [request responseString];
}
- (void)requestFail:(ASIHTTPRequest *)request
{
NSError *error = [request error];
}
ASIHttpRequest本身就是一个NSOperation的子类。也就是说它可以直接被放到“任务队列”中并列执行
1)可以设置一个上下文到request对象中,当请求响应完后可以通过访问request对象的userinfo获取里面的信息
2)为每一个请求实例设置不同的setDidFinishSelector/setDidFaildSelector的回调方法
3)子类化ASIHttpRequest,重写requestFinished与failWithProblem:方法
ASINetworkQueue的delegate
requestDidStartSelector:请求发起时会调此方法,可以在此方法中根据业务选择性的设置request对象的delegate
requestDidReceiveResponseHeadersSelector:当接受完响应的Header后设计次方法,这个对下载大数据的时候相当有用,可以在方法里做更多业务上的处理
requestDidFinishSelector:请求并响应成功完成时调用此方法
requestDidFailSelector:请求失败
queueDidFinishSelector:整个队列里的所有请求都结束时调用此方法
ASINetworkQueue是NSOperationQueues的扩展,小而强大。但也与它的父类略有区别。如:仅添加到队列中其实并不能执行请求,只有调用[queue go]才会执行;一个正在运行的队列,并不需要重复调用[queue go]。默认情况下,队列中的一个请求如果失败,会取消所有未完成的请求。可以设置[queue setShouldCancelAllRequestOnFailure:NO]来修正
取消异步请求
注:同步请求是不能被取消的
不管是队列请求还是简单的异步请求,全部调用[request cancel]来取消请求。取消的请求默认都会按照请求失败处理,并调用请求失败delegate。如果不想调用delegate方法,则设置[request clearDelegateAndCancel];
队列中请求中需要注意的是。如果取消了一个请求,队列会自动取消其它所有请求。如果只想取消一个请求,可以设置队列:[queue setShouldCancelAllRequestOnFailure:NO];如果想明确取消所有请求:[queue cancelAllOperation];
安全内存回收建议:request并没有retain delegate,所以在没有请求完的时候释放了此delegate,需要在delloc方法里先取消所有请求,再释放请求实例,ARC环境下不需要考虑那么多了
向服务器上传数据:ASIFormDataRequest
模拟Form表单提交,其提交格式与Header会自动识别。
没有文件:application/x-www-form-urlencoded
有文件:multipart/form-data
NSURL *url = [NSURL URLWithString:@"http://www.testURL.com"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"Ben" forKey:@"first_name"];
[request setPostValue:@"Copsy" forKey:@"last_name"];
[request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];
[request addData:imageData withFileName:@"ben.jpg" andContentType:@"image/jpeg" forKey:@"photos"];
发送自定义数据
NSURL *url = [NSURL URLWithString:@"http://www.testURL.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request appendPostData:[@"form data" dataUsingEncoding:NSUTF8StringEncoding]];
[request setRequestMethod:@"POST"];
下载文件
通过设置request的setDownloadDestinationPath,可以设置下载文件用的下载目标目录
下载文件会保存在temporaryFileDownloadPath目录下。下载完会做以下事情
1)如果数据是压缩的,进行压缩,并把文件放在downloadDestinationPath目录中,临时文件删除
2)如果下载失败,临时文件被直接移到downloadDestinationPath目录,并替换同名文件
如果想获取下载中的所有数据,可以实现delegate中的request:didReceiveData:方法。但如果实现了这个方法,request在下载完后,request并不把文件放在downloadDestinationPath中,需要手工处理
获取下载进度
信息:status,header,responseEncoding
[request responseStatusCode];
[[request responseHeaders] objectForKey:@"X-Powered-By"];
[request responseEncoding];
获取请求进度
两个获取请求进度的回调方法
downloadProgressDelegate//获取下载进度
uploadProgressDelegate//获取上传进度
cookie支持
如果cookie支持的话,会把这些信息放在NSHTTPCookieStorage容器中共享,并供下次使用。可以用[ASIHTTPRequest setSessionCookies:nil];清空所有cookie。当然,也可以取消默认的cookie策略,使用自定义的cookie:
NSDictionary *properties = [[NSMutableDictionary alloc] init];
[properties setValue:@"Test Value" 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];
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];
大文件断点续传
只需要设置
[request setAllowResumeForFileDownloads:YES];
[request setDownloadDestinationPath:downloadPath];