发起一个同步请求
建立一个异步请求
队列请求
请求队列上下文
ASINetworkQueues, 它的delegate提供更为丰富的功能
取消异步请求
安全的内存回收建议
向服务器端上传数据
下载文件
获取响应信息
获取请求进度
cookie的支持
大文件断点续传
ASIDownloadCache 设置下载缓存
多种的缓存并存
缓存策略
缓存存储方式
缓存其它特性
实现自定义的缓存
使用代理请求
ASIHTTPRequest, 请求的其它特性 缓存
ASIHTTPRequest是一款极其强劲的HTTP访问开源项目。让简单的API完成复杂的功能, 安全
如:
异步请求,队列请求,GZIP压缩,缓存,断点续传,进度跟踪,上传文件,HTTP认证
在新的版本中,还加入了Objective-C闭包Block的支持,让咱们的代码更加轻简灵活。 服务器
下面就举例说明它的API用法。 cookie
同步意为着线程阻塞,在主线程中使用此方法会使应用Hang住而不响应任何用户事件。因此,在应用程序设计时,大多被用在专门的子线程增长用户体验,或用异步请求代替(下面会讲到)。 网络
- (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, 因为是同步请求,没有基于事件的回调方法,因此从request的error属性获取错误信息。
d, responseString,为请求的返回NSString信息。 session
异步请求的好处是不阻塞当前线程,但相对于同步请求略为复杂,至少要添加两个回调方法来获取异步事件。
下面异步请求代码完成上面一样的一件事情: 闭包
- (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来启动网络请求。
b,在这里实现了两个delegate的方法,当数据请求成功时会调用requestFinished,请求失败时(如网络问题或服务器内部错误)会调用requestFailed。 架构
提供了一个对异步请求更加精准丰富的控制。
如,能够设置在队列中,同步请求的链接数。往队列里添加的请求实例数大于maxConcurrentOperationCount时,请求实例将被置为等待,直到前面至少有一个请求完成并出列才被放到队列里执行。
也适用于当咱们有多个请求需求按顺序执行的时候(多是业务上的须要,也多是软件上的调优),仅仅须要把maxConcurrentOperationCount设为“1”。 app
- (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];
}
|
建立NSOperationQueue,这个Cocoa架构的执行任务(NSOperation)的任务队列。咱们经过 ASIHTTPRequest.h的源码能够看到,此类自己就是一个NSOperation的子类。也就是说它能够直接被放到"任务队列"中,并被执行。 上面的代码队了队列的建立与添加操做外,其它代码与上一例同样。 异步
a,能够设置一个上下文(userInfo)到request对象中,当请求响应完后能够经过访问request对象的userInfo获取里面的信息
b,为每个请求实例设置不一样的setDidFinishSelector / setDidFailSelector的回调方法
c,子类化ASIHTTPRequest,重写requestFinished: 与 failWithProblem:方法
提供的更多的回调方法以下:
a,requestDidStartSelector,请求发起时会调此方法,你能够在此方法中跟据业务选择性的设置request对象的deleaget。
b,requestDidReceiveResponseHeadersSelector,当接受完响应的Header后设计此方法,这个对下载大数据的时候至关有用,你能够在方法里作更多业务上的处理。
c,requestDidFinishSelector,请求并响应成功完成时调用此方法
d,requestDidFailSelector,请求失败
e,queueDidFinishSelector,整个队列里的全部请求都结束时调用此方法。
|
它是NSOperationQueues的扩展,小而强大。但也与它的父类略有区别。如,仅添加到队列中其实并不能执行请求,只有调用[ queue g o]才会执行;一个正在运行中的队列,并不须要重复调用[ queue go ]。 默认状况下,队列中的一个请求若是失败,它会取消全部未完成的请求。能够设置[ queue setShouldCancelAllRequestsOnFailure:NO ]来修 正。 |
首先,同步请求是不能取消的。
其次,不论是队列请求,仍是简单的异步请求,所有调用[ request cancel ]来取消请求。
|
取消的请求默认都会按请求失败处理,并调用请求失败delegate。 若是不想调用delegate方法,则设置:[ request clearDelegatesAndCancel]; |
队列请求中须要注意的是,若是你取消了一个请求,队列会自动取消其它全部请求。
若是只想取消一个请求,能够设置队列:[ queue setShouldCancelAllRequestsOnFailure:NO ];
若是想明确取消全部请求:[ queue cancelAllOperations ];
request并无retain你的delegate,因此在没有请求完的时候释放了此delegate,须要在dealloc方法里先取消全部请求,再释放请求实例,如:
- (void)dealloc
{
[request clearDelegatesAndCancel];
[request release];
...
[super dealloc];
}
|
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"];
|
若是要发送自定义数据:
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"];
|
//用户自定义数据 字典类型 (可选)
request.userInfo = [NSDictionary dictionaryWithObject:method forKey:@"Method"];
//post的数据
[request appendPostData:[body dataUsingEncoding:NSUTF8StringEncoding]]
经过设置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];
|
有两个回调方法能够获取请求进度,
1,downloadProgressDelegate,能够获取下载进度
2,uploadProgressDelegate,能够获取上传进度
若是Cookie存在的话,会把这些信息放在NSHTTPCookieStorage容器中共享,并供下次使用。
你能够用[ ASIHTTPRequest setSessionCookies:nil ] ; 清空全部Cookies。
固然,你也能够取消默认的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]);
|
0.94之后支持大文件的断点下载,只须要设置:
[ request setAllowResumeForFileDownloads:YES ];
[ request setDownloadDestinationPath:downloadPath ];
就能够了。
ASIHTTPRequest会自动保存访问过的URL信息,并备以后用。在如下几个场景很是有用:
1,当没有网络链接的时候。
2,已下载的数据再次请求时,仅当它与本地版本不样时才进行下载。
它对Get请求的响应数据进行缓存(被缓存的数据必需是成功的200请求):
[ASIHTTPRequest setDefaultCache:[ASIDownloadCache sharedCache]];
|
当设置缓存策略后,全部的请求都被自动的缓存起来。
另外,若是仅仅但愿某次请求使用缓存操做,也能够这样使用:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadCache:[ASIDownloadCache sharedCache]];
|
仅仅须要建立不一样的ASIDownloadCache,并设置缓存所使用的路径,并设置到须要使用的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]];
|
缓存策略是咱们控制缓存行为的主要方式,如:何时进行缓存,缓存数据的利用方式。
如下是策略可选列表(可组合使用):
ASIUseDefaultCachePolicy | 这是一个默认的缓存策略“ASIAskServerIfModifiedWhenStaleCachePolicy”,这个很明白,见名知意(它不能与其它策略组合使用) |
---|---|
ASIDoNotReadFromCacheCachePolicy | 所读数据不使用缓存 |
ASIDoNotWriteToCacheCachePolicy | 不对缓存数据进行写操做 |
ASIAskServerIfModifiedWhenStaleCachePolicy | 默认缓存行为,request会先判断是否存在缓存数据。a, 若是没有再进行网络请求。 b,若是存在缓存数据,而且数据没有过时,则使用缓存。c,若是存在缓存数据,但已通过期,request会先进行网络请求,判断服务器版本与本地版本是 否同样,若是同样,则使用缓存。若是服务器有新版本,会进行网络请求,并更新本地缓存 |
ASIAskServerIfModifiedCachePolicy | 与默认缓存大体同样,区别仅是每次请求都会 去服务器判断是否有更新 |
ASIOnlyLoadIfNotCachedCachePolicy | 若是有缓存在本地,无论其过时与否,总会拿来使用 |
ASIDontLoadCachePolicy | 仅当有缓存的时候才会被正确执行,若是没有缓存,request将被取消(没有错误信息) |
ASIFallbackToCacheIfLoadFailsCachePolicy | 这个选项常常被用来与其它选项组合使用。请求失败时,若是有缓存当网络则返回本地缓存信息(这个在处理异常时很是有用) |
|
若是设置了“defaultCachePolicy”则全部的请求都会使用此缓存。 |
你能够设置缓存的数据须要保存多长时间,ASIHTTPRequest提供了两种策略:
a,ASICacheForSessionDurationCacheStoragePolicy,默认策略,基于session的缓存数据存储。当下次运行或[ASIHTTPRequest clearSession]时,缓存将失效。
b,ASICachePermanentlyCacheStoragePolicy,把缓存数据永久保存在本地,
如:
ASIHTTPRequest *request = [ ASIHTTPRequest requestWithURL:url ];
[ request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy ];
|
另外,也可使用clearCachedResponsesForStoragePolicy来清空指定策略下的缓存数据。
设置是否按服务器在Header里指定的是否可被缓存或过时策略进行缓存:
[[ ASIDownloadCache sharedCache ] setShouldRespectCacheControlHeaders:NO ];
|
设置request缓存的有效时间:
[ request setSecondsToCache:60*60*24*30 ]; // 缓存30天
|
能够判断数据是否从缓存读取:
[ request didUseCachedResponse ];
|
设置缓存所使用的路径:
[ request setDownloadDestinationPath:[[ ASIDownloadCache sharedCache ] pathToStoreCachedResponseDataForRequest:request ]];
|
只要简单的实现ASICacheDelegate接口就能够被用来使用。
默认的状况下,ASIHTTPRequest会使用被设置的默认代理。但你也能够手动修改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"]];
|
iOS4中,当应用后台运行时仍然请求数据:
[ request setShouldContinueWhenAppEntersBackground:YES ];
|
是否有网络请求:
[ ASIHTTPRequest isNetworkInUse ]
|
是否显示网络请求信息在status bar上:
[ ASIHTTPRequest setShouldUpdateNetworkActivityIndicator:NO ];
|
设置请求超时时,设置重试的次数:
[ 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 ];
|