第三方苹果开发库之ASIHTTPRequest分类:IOS 发布时间:2012/10/18 22:03:54
相关网络资料:
ASIHttpRequest库简介、配置和安装使用ASIHTTPRequest可以很方便的进行一下操作:
等等,只要跟HTTP有关,只有你想不到的,没有她做不到的~ 配置方法:
iPhone 工程还需要:
库引用: CFNetwork.framework SystemConfiguration.framework MobileCoreServices.framework
另外,还需要libxml2.dylib(libxml2还需要设置连接选项-lxml2 和头文件搜索路径/usr/include/libxml2)
ASIHttpRequest-创建和执行request同步请求 同步请求会在当前线程中执行,使用error属性来检查结束状态(要下载大文件,则需要设定downloadDestinationPath来保存文件到本地): - (IBAction)grabURL:(id)sender { NSURL *url = [NSURL URLWithString:@"http://www.dreamingwish.com"]; ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request startSynchronous]; NSError *error = [request error]; if (!error) { NSString *response = [request responseString]; } }
异步请求下面是最简单的异步请求方法,这个request会在全局的NSOperationQueue中执行,若要进行更复杂的操作,我们需要自己创建NSOperationQueue或者ASINetworkQueue,后面会讲到。 - (IBAction)grabURLInBackground:(id)sender { NSURL *url = [NSURL URLWithString:@"http://www.dreamingwish.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]; } 使用block在平台支持情况下,ASIHTTPRequest1.8以上支持block。 - (IBAction)grabURLInBackground:(id)sender { NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"]; __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request setCompletionBlock:^{ // Use when fetching text data NSString *responseString = [request responseString]; // Use when fetching binary data NSData *responseData = [request responseData]; }]; [request setFailedBlock:^{ NSError *error = [request error]; }]; [request startAsynchronous]; } 注意,声明request时要使用__block修饰符,这是为了告诉block不要retain request,以免出现retain循环,因为request是会retain block的。
使用队列创建NSOperationQueue或者ASINetworkQueue队列,我们还可以设定最大并发连接数:maxConcurrentOperationCount - (IBAction)grabURLInTheBackground:(id)sender { if (![self queue]) { [self setQueue:[[[NSOperationQueue alloc] init] autorelease]]; [self queue].maxConcurrentOperationCount = 4; } NSURL *url = [NSURL URLWithString:@"http://www.dreamingwish.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]; } 如果不设定selector,那么系统会使用默认的requestFinished: 和 requestFailed:方法 如果需要对队列里面的每个request进行区分,那么可以设定request的userInfo属性,它是个NSDictionary,或者更简单的方法是设定每个request的tag属性,这两个属性都不会被发送到服务器。
对于ASINetworkQueueASINetworkQueue是NSOperationQueue的子类,提供更高级的特性(ASINetworkQueue的代理函数):
ASINetworkQueues与NSOperationQueues稍有不同,加入队列的request不会立即开始执行。如果队列打开了进度开关,那么队列开始时,会先对所有GET型request进行一次HEAD请求,获得总下载大小,然后真正的request才被执行。
当ASINetworkQueue中的一个request失败时,默认情况下,ASINetworkQueue会取消所有其他的request。要禁用这个特性,设置 [queue setShouldCancelAllRequestsOnFailure:NO]。 ASINetworkQueues只可以执行ASIHTTPRequest操作,二不可以用于通用操作。试图加入一个不是ASIHTTPRequest的NSOperation将会导致抛出错误。 取消异步请求取消一个异步请求(无论request是由[request startAsynchronous]开始的还是从你创建的队列中开始的),使用[request cancel]即可。注意同步请求不可以被取消。 注意,如果你取消了一个request,那么这个request将会被视为请求失败,并且request的代理或者队列的代理的失败代理函数将被调用。如果你不想让代理函数被调用,那么将delegate设置为nil,或者使用clearDelegatesAndCancel方法来取消request。 clearDelegatesAndCancel 将会首先清除所有的代理和block。 当使用ASINetworkQueue时,如果取消了队列中的一个request,那么队列中其他所有request都会被取消,可以设置shouldCancelAllRequestsOnFailure的值为NO来避免这个现象。 安全地控制delegate防止request完成之前代理被释放request并不retain它们的代理,所以有可能你已经释放了代理,而之后request完成了,这将会引起崩溃。大多数情况下,如果你的代理即将被释放,你一定也希望取消所有request,因为你已经不再关心它们的返回情况了。如此做: // 代理类的dealloc函数 - (void)dealloc { [request clearDelegatesAndCancel]; [request release]; ... [super dealloc]; } ASIHttpRequest-发送数据发送数据 设定request头ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request addRequestHeader:@"Referer" value:@"http://www.dreamingwish.com/"]; 使用ASIFormDataRequest POST表单通常数据是以’application/x-www-form-urlencoded’格式发送的,如果上传了二进制数据或者文件,那么格式将自动变为‘multipart/form-data’ 文件中的数据是需要时才从磁盘加载,所以只要web server能处理,那么上传大文件是没有问题的。 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"]; 数据的mime头是自动判定的,但是如果你想自定义mime头,那么这样: ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
// Upload a file on disk
[request setFile:@"/Users/ben/Desktop/ben.jpg" withFileName:@"myphoto.jpg" andContentType:@"image/jpeg"
forKey:@"photo"];
// Upload an NSData instance
[request setData:imageData withFileName:@"myphoto.jpg" andContentType:@"image/jpeg" forKey:@"photo"]; 你可以使用addPostValue方法来发送相同name的多个数据(梦维:服务端会以数组方式呈现): ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:@"Ben" forKey:@"names"];
[request addPostValue:@"George" forKey:@"names"];
[request addFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photos"];
[request addData:imageData withFileName:@"george.jpg" andContentType:@"image/jpeg" forKey:@"photos"]; PUT请求、自定义POST请求如果你想发送PUT请求,或者你想自定义POST请求,使用appendPostData: 或者 appendPostDataFromFile: 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"]; ASIHTTPRequest-下载数据将服务器响应数据直接下载到文件如果你请求的资源很大,你可以直接将数据下载到文件中来节省内存。此时,ASIHTTPRequest将不会一次将返回数据全部保持在内存中。 ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:@"/Users/ben/Desktop/my_file.txt"]; 当我们把数据下载到downloadDestinationPath时,数据将首先被存在临时文件中。此时文件的路径名存储在temporaryFileDownloadPath中(梦维:如果不设置这个值,会自动生成一个文件名,在模拟器中,文件被创建在$TMPDIR中)。当request完成时,会发生下面两件事之一:
处理收到的服务器响应数据如果你想处理服务器响应的数据(例如,你想使用流解析器对正在下载的数据流进行处理),你应该实现代理函数 request:didReceiveData:。注意如果你这么做了,ASIHTTPRequest将不会填充responseData到内存,也不会将数据写入文件(downloadDestinationPath )——你必须自己搞定这两件事(之一)。
获取HTTP状态码ASIHTTPRequest并不对HTTP状态码做任何处理(除了重定向和授权状态码,下面会介绍到),所以你必须自己检查状态值并正确处理。 ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
int statusCode = [request responseStatusCode];
NSString *statusMessage = [request responseStatusMessage]; 读取响应头ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSString *poweredBy = [[request responseHeaders] objectForKey:@"X-Powered-By"];
NSString *contentType = [[request responseHeaders] objectForKey:@"Content-Type"];
处理文本编码ASIHTTPRequest会试图读取返回数据的编码信息(Content-Type头信息)。如果它发现了编码信息,它会将编码信息设定为合适的 NSStringEncoding.如果它没有找到编码信息,它会将编码设定为默认编码(NSISOLatin1StringEncoding)。 当你调用[request responseString],ASIHTTPRequest会尝试以responseEncoding将返回的Data转换为NSString。
处理重定向当遇到以下HTTP状态码之一时,ASIHTTPRequest会自动重定向到新的URL:
当发生重定向时,响应数据的值(responseHeaders,responseCookies,responseData,responseString等等)将会映射为最终地址的相应返回数据。 当URL发生循环重定向时,设置在这个URL上的cookie将被储存到全局域中,并在适当的时候随重定向的请求发送到服务器。
你可以关闭自动重定向:将shouldRedirect设置为NO。
ASIHTTPRequest-进度追踪每个ASIHTTPRequest有两个delegate用来追踪进度:
进度delegate可以是NSProgressIndicators (Mac OS X) 或者 UIProgressViews (iPhone).ASIHTTPRequest会自适应这两个class的行为。你也可以使用自定义class作为进度delegate,只要它响应setProgress:函数。
追踪单个request的下载进度这个例子中, myProgressIndicator是个 NSProgressIndicator. ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadProgressDelegate:myProgressIndicator];
[request startSynchronous];
NSLog(@"Max: %f, Value: %f", [myProgressIndicator maxValue],[myProgressIndicator doubleValue]); 追踪一系列request的下载进度在这个例子中, myProgressIndicator 是个 UIProgressView, myQueue是个 ASINetworkQueue. - (void)fetchThisURLFiveTimes:(NSURL *)url
{
[myQueue cancelAllOperations];
[myQueue setDownloadProgressDelegate:myProgressIndicator];
[myQueue setDelegate:self];
[myQueue setRequestDidFinishSelector:@selector(queueComplete:)];
int i;
for (i=0; i<5; i++) {
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[myQueue addOperation:request];
}
[myQueue go];
}
- (void)queueComplete:(ASINetworkQueue *)queue
{
NSLog(@"Value: %f", [myProgressIndicator progress]);
} 这个例子中,我们已经为ASINetworkQueues调用过[myQueue go]了。
追踪单个request的上传进度在这个例子中, myProgressIndicator 是个 UIProgressView。 ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"Ben" forKey:@"first_name"];
[request setPostValue:@"Copsey" forKey:@"last_name"];
[request setUploadProgressDelegate:myProgressIndicator];
[request startSynchronous];
NSLog(@"Value: %f",[myProgressIndicator progress]);
追踪一系列request的上传进度这个例子中, myProgressIndicator是个 NSProgressIndicator, myQueue是个ASINetworkQueue. - (void)uploadSomethingFiveTimes:(NSURL *)url
{
[myQueue cancelAllOperations];
[myQueue setUploadProgressDelegate:myProgressIndicator];
[myQueue setDelegate:self];
[myQueue setRequestDidFinishSelector:@selector(queueComplete:)];
int i;
for (i=0; i<5; i++) {
ASIHTTPRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostBody:[@"Some data" dataUsingEncoding:NSUTF8StringEncoding]];
[myQueue addOperation:request];
}
[myQueue go];
}
- (void)queueComplete:(ASINetworkQueue *)queue
{
NSLog(@"Max: %f, Value: %f", [myProgressIndicator maxValue],[myProgressIndicator doubleValue]);
}
精确进度条vs简单进度条ASIHTTPRequest提供两种进度条显示,简单进度条和精确进度条,使用ASIHTTPRequests 和ASINetworkQueues的showAccurateProgress 来控制。为一个request设置showAccurateProgress只会对该request有效。如果你为一个队列设置showAccurateProgress,那么会影响队列里所有的request。 简单进度条当使用简单进度条时,进度条只会在一个request完成时才更新。对于单个request,这意味着你只有两个进度状态:0%和100%。对于一个有5个request的队列来说,有五个状态:0%,25%,50%,75%,100%,每个request完成时,进度条增长一次。 简单进度条(showAccurateProgress = NO)是ASINetworkQueue的默认值,适用于大量小数据请求。 精确进度条当使用精确进度条时,每当字节被上传或下载时,进度条都会更新。它适用于上传/下载大块数据的请求,并且会更好的显示已经发送/接收的数据量。 使用精确进度条追踪上传会轻微降低界面效率,因为进度delegate(一般是UIProgressViews 或NSProgressIndicators)会更频繁地重绘。 使用精确进度条追踪下载会更影响界面效率,因为队列会先为每个GET型request进行HEAD请求,以便统计总下载量。强烈推荐对下载大文件的队列使用精确进度条,但是要避免对大量小数据请求使用精确进度条。 精确进度条(showAccurateProgress = YES)是以同步方式执行的ASIHTTPRequest的默认值。
自定义进度追踪ASIProgressDelegate 协议定义了所有能更新一个request进度的方法。多数情况下,设置你的uploadProgressDelegate或者 downloadProgressDelegate为 NSProgressIndicator或者UIProgressView会很好。但是,如果你想进行更复杂的追踪,你的进度delegate实现下列函数要比 setProgress: (iOS) 或者 setDoubleValue: / setMaxValue: (Mac)好: 这些函数允许你在实际量的数据被上传或下载时更新进度,而非简单方法的0到1之间的数字。 downloadProgressDelegates方法
uploadProgressDelegates方法
ASIHTTPRequest-身份验证你可以查阅ASIHTTPRequest授权流程图来了解ASIHTTPRequest如何找到授权凭据,并将授权凭据应用到request上。 为URL指定要使用的用户名和密码NSURL *url = [NSURL URLWithString:@"http://www.dreamingwish.com/"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 为request指定要使用的用户名和密码NSURL *url = [NSURL URLWithString:@"http://www.dreamingwish.com/"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setUsername:@"username"];
[request setPassword:@"password"]; 将凭据存储到keychain如果打开了keychainPersistence,所有提供的可用的用户名和密码将被存储到keychain中,以后的request将会重用这些用户名密码,即使你关闭程序后重新打开也不影响。 NSURL *url = [NSURL URLWithString:@"http://www.dreamingwish.com/"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setUseKeychainPersistence:YES];
[request setUsername:@"username"];
[request setPassword:@"password"]; 如果你使用keychain但是想要自己管理它,你可以在ASIHTTPRequest.h文件里找到相关的类方法。 将凭据存储到session中如果打开了useSessionPersistence(默认即是如此),ASIHTTPRequest会把凭据存储到内存中,后来的request将会重用这些凭据。 NSURL *url = [NSURL URLWithString:@"http://www.dreamingwish.com/"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setUsername:@"username"];
[request setPassword:@"password"];
[request setUseSessionPersistence:YES]; //这一项是默认的,所以并不必要
//将会重用我们的 username 和 password
request = [ASIHTTPRequest requestWithURL:url]; NTLM授权要使用NTLM授权的Windows服务器,你还需要指定你要进行授权域。 NSURL *url = [NSURL URLWithString:@"http://www.dreamingwish.com/"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setUsername:@"username"];
[request setPassword:@"password"];
[request setDomain:@"my-domain"]; 使用代理来提供凭据你不一定非要提前指定授权凭据,你还可以让每个request在无法从session或keychain中找到凭据时向它们的代理请求凭据。如果你要连接到一个你并不清楚授权类型的服务器时,这是很有用的。 你的delegate必须实现authenticationNeededForRequest:方法,当request等待凭据时,ASIHTTPRequest将会暂停这个request。如果你持有你需要的凭据,那么先为request设定凭据,然后调用[request retryUsingSuppliedCredentials]即可。如果你想取消授权,调用[request cancelAuthentication],此时,这个request也会被取消。 从1.0.8版开始,一次只能有一个request的delegate收到authenticationNeededForRequest: 或者 proxyAuthenticationNeededForRequest:。当delegate处理第一个request时,其他需要授权的request将会被暂停。如果提供了一个凭据,当前进程中所有其他的request将会假定这个凭据对这个URL有效,并尝试重用这个凭据。如果delegate取消了授权,并且队列的shouldCancelAllRequestsOnFailure值为YES,所有其他的request都将被取消(它们也不会尝试请求凭据)。
使用内建的授权对话框(目前只对iOS有效)
这个特性归功于1.0.8版本的新类ASIAuthenticationDialog 。这个特性主要是用于授权代理(后面会介绍到),但是它也可以用来向用户取得授权凭据。 为了更好的用户体验,大多数(连接单一服务的)app必须为request的delegate实现authenticationNeededForRequest:方法,或者避免同时使用代理式授权。
但是,会有一些情况下,为普通的授权使用ASIHTTPRequest的标准授权对话框更好:
对于这些情况,为request设置shouldPresentAuthenticationDialog为YES,此时,如果你的代理没有实现 authenticationNeededForRequest:方法,那么用户将会看到这个对话框。 一次同时只有一个对话框可以显示出来,所以当一个对话框显示时,所有其他需要授权的request将会暂停。如果提供了一个凭据,当前进程中所有其他的request将会假定这个凭据对这个URL有效,并尝试重用这个凭据。如果delegate取消了授权,并且队列的shouldCancelAllRequestsOnFailure值为YES,所有其他的request都将被取消(它们也不会尝试请求凭据)。 对于同步请求的request,授权对话框不会显示出来。 这个对话框部分模仿了iPhone上Safari使用的授权对话框,它包含以下内容:
如果你想改变它的外观,你必须继承ASIHTTPRequest,并重写showAuthenticationDialog来显示你自己的对话框或ASIAuthenticationDialog子类。 在服务器请求凭据前向服务器发送凭据
在第一次生成request时,ASIHTTPRequest可以先向服务器发送凭据(如果有的话),而不是等服务器要求提供凭据时才提供凭据。这个特性可以提高使用授权的程序的执行效率,因为这个特性避免了多余的request。 对于基本授权模式,要触发这个行为,你必须手动设置request的authenticationScheme为kCFHTTPAuthenticationSchemeBasic: [request setAuthenticationScheme:(NSString *)kCFHTTPAuthenticationSchemeBasic]; 对于其他授权方案,凭据也可以在服务器要求之前被发送,但是仅当有另一个request成功授权之后才行。 在以下情况下,你也许想要禁用这个特性:
要禁用这个特性,这样做: [request setShouldPresentCredentialsBeforeChallenge:NO];
ASIHTTPRequest-HTTP授权-流程图
ASIHTTPRequest-Cookie的使用持久化cookieASIHTTPRequest允许你使用全局存储来和所有使用CFNetwork或者NSURLRequest接口的程序共享cookie。 如果设置useCookiePersistence为YES(默认值),cookie会被存储在共享的 NSHTTPCookieStorage 容器中,并且会自动被其他request重用。值得一提的是,ASIHTTPRequest会向服务器发送其他程序创建的cookie(如果这些cookie对特定request有效的话)。 你可以清空session期间创建的所有cookie: [ASIHTTPRequest setSessionCookies:nil]; 这里的‘session cookies’指的是一个session中创建的所有cookie,而非没有过期时间的cookie(即通常所指的会话cookie,这种cookie会在程序结束时被清除)。 另外,有个方便的函数 clearSession可以清除session期间产生的所有的cookie和缓存的授权数据。
自己处理cookie如果你愿意,你大可以关闭useCookiePersistence,自己来管理某个request的一系列cookie: //创建一个cookie
NSDictionary *properties = [[[NSMutableDictionary alloc] init] autorelease];
[properties setValue:[@"Test Value" encodedCookieValue] forKey:NSHTTPCookieValue];
[properties setValue:@"ASIHTTPRequestTestCookie" forKey:NSHTTPCookieName];
[properties setValue:@".dreamingwish.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];
//这个url会返回名为''ASIHTTPRequestTestCookie''的cookie的值
url = [NSURL URLWithString:@"http://www.dreamingwish.com/"];
request = [ASIHTTPRequest requestWithURL:url];
[request setUseCookiePersistence:NO];
[request setRequestCookies:[NSMutableArray arrayWithObject:cookie]];
[request startSynchronous];
//将会打印: I have ''Test Value'' as the value of ''ASIHTTPRequestTestCookie''
NSLog(@"%@",[request responseString]); ASIHTTPRequest-数据压缩使用gzip来处理压缩的响应数据从0.9版本开始,ASIHTTPRequest会提示服务器它可以接收gzip压缩过的数据。 许多web服务器可以在数据被发送之前压缩这些数据——这可以加快下载速度减少流量使用,但会让服务器的cpu(压缩数据)和客户端(解压数据)付出代价。总的来说,只有特定的几种数据会被压缩——许多二进制格式的文件像jpeg,gif,png,swf和pdf已经压缩过他们的数据了,所以向客户端发送这些数据时不会进行gzip压缩。文本文件例如网页和xml文件会被压缩,因为它们通常有大量的数据冗余。
怎样设置apache的mod_deflate来使用gzip压缩数据apache 2.x以上版本已经配备了mod_deflate扩展,这使得apache可以透明地压缩特定种类的数据。要开启这个特性,你需要在apache的配置文件中启用mod_deflate。并将mod_deflate命令添加到你的虚拟主机配置或者.htaccess文件中。
在ASIHTTPRequest中使用gzip- (IBAction)grabURL:(id)sender
{
NSURL *url = [NSURL URLWithString:@"http://www.dreamingwish.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
// 默认为YES, 你可以设定它为NO来禁用gzip压缩
[request setAllowCompressedResponse:YES];
[request startSynchronous];
BOOL *dataWasCompressed = [request isResponseCompressed]; // 响应是否被gzip压缩过?
NSData *compressedResponse = [request rawResponseData]; // 压缩的数据
NSData *uncompressedData = [request responseData]; // 解压缩后的数据
NSString *response = [request responseString]; // 解压缩后的字符串
} 当allowCompressedResponse 设置为YES时,ASIHTTPRequest将向request中增加一个Accept-Encoding头,表示我们可以接收gzip压缩过的数据。如果响应头中包含一个Content-Encoding头指明数据是压缩过的,那么调用responseData 或者responseString 将会得到解压缩后的数据。你也可以通过调用rawResponseData来获得原始未压缩的数据。
相应数据的实时解压缩默认情况下,ASIHTTPRequest会等到request完成时才解压缩返回的数据。若设置request的shouldWaitToInflateCompressedResponses 属性为NO,ASIHTTPRequest将会对收到的数据进行实时解压缩。 在某些情况下,这会稍稍提升速度,因为数据可以在reqeust等待网络数据时进行处理。 如果你需要对响应数据流进行流处理(例如XML和JSON解析),这个特性会很有用。如果启用了这个选项,你可以通过实现代理函数request:didReceiveData:来将返回的网络数据一点一点喂给解析器。 注意,如果shouldWaitToInflateCompressedResponses 被设置为NO,那么原始(未解压)的数据会被抛弃。具体情况请查阅ASIHTTPRequest.h的代码注释。
使用gzip压缩request数据1.0.3版本的新特性就是gzip压缩request数据。使用这个特性,你可以通过设置shouldCompressRequestBody 为YES来使你的程序压缩POST/PUT的内容,默认值为NO。 apache的mod_deflate可以自动解压缩gzip压缩的请求体(通过合适的设置)。这个方法适用于CGI内容,但不适用于内容过滤器式的模块(例如mod PHP),这种情况下,你就必须自己解压缩数据。
ASIHTTPRequest-断点续传(下载)从0.94版本开始,ASIHTTPRequest可以恢复中断的下载 - (IBAction)resumeInterruptedDownload:(id)sender
{
NSURL *url = [NSURL URLWithString:
@"http://www.dreamingwish.com/wp-content/uploads/2011/10/asihttprequest-auth.png"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
NSString *downloadPath = @"/Users/ben/Desktop/asi.png";
//当request完成时,整个文件会被移动到这里
[request setDownloadDestinationPath:downloadPath];
//这个文件已经被下载了一部分
[request setTemporaryFileDownloadPath:@"/Users/ben/Desktop/asi.png.download"];
[request setAllowResumeForFileDownloads:YES];
[request startSynchronous];
//整个文件将会在这里
NSString *theContent = [NSString stringWithContentsOfFile:downloadPath];
} 这个特性只对下载数据到文件中有效,你必须为一下情况的request设置allowResumeForFileDownloads 为YES:
另外,你必须自己设置一个临时下载路径(setTemporaryFileDownloadPath),这个路径是未完成的数据的路径。新的数据将会被添加到这个文件,当下载完成时,这个文件将被移动到downloadDestinationPath 。 断点续传的工作原理是读取temporaryFileDownloadPath的文件的大小,并使用Range: bytes=x HTTP头来请求剩余的文件内容。
ASIHTTPRequest-直接读取磁盘数据流的请求体从0.96版本开始,ASIHTTPRequest可以使用磁盘上的数据来作为请求体。这意味着不需要将文件完全读入内存中,这就避免的当使用大文件时的严重内存消耗。 使用这个特性的方法有好几种: ASIFormDataRequestsNSURL *url = [NSURL URLWithString:@"http://www.dreamingwish.com/"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"foo" forKey:@"post_var"];
[request setFile:@"/Users/ben/Desktop/bigfile.txt" forKey:@"file"];
[request startSynchronous]; 当使用setFile:forKey:时,ASIFormDataRequests 自动使用这个特性。request将会创建一个包含整个post体的临时文件。文件会一点一点写入post体。这样的request是由CFReadStreamCreateForStreamedHTTPRequest创建的,它使用文件读取流来作为资源。 普通ASIHTTPRequest如果你明白自己的request体会很大,那么为这个request设置流式读取模式。 [request setShouldStreamPostDataFromDisk:YES]; 下面的例子中,我们将一个NSData对象添加到post体。这有两个方法:从内存中添加(appendPostData:),或者从文件中添加(appendPostDataFromFile:); NSURL *url = [NSURL URLWithString:@"http://www.dreamingwish.com/"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setShouldStreamPostDataFromDisk:YES];
[request appendPostData:myBigNSData];
[request appendPostDataFromFile:@"/Users/ben/Desktop/bigfile.txt"];
[request startSynchronous]; 这个例子中,我们想直接PUT一个大文件。我们得自己设置setPostBodyFilePath ,ASIHTTPRequest将使用这个文件来作为post体。 NSURL *url = [NSURL URLWithString:@"http://www.dreamingwish.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:@"PUT"];
[request setPostBodyFilePath:@"/Users/ben/Desktop/another-big-one.txt"];
[request setShouldStreamPostDataFromDisk:YES];
[request startSynchronous];
ASIHTTPRequest-使用download cache
ASIHTTPRequest可以自动缓存下载的数据。在很多情况下这很有用:
在之前版本的ASIHTTPRequest里,遇到上述情况,你只能自己处理这些策略。在一些情况下,使用download cache可以让你不用再写本地缓存机制。 ASIDownloadCache 是个简单的URL cache,可以用来缓存GET请求的相应数据。一个request要被缓存,它首先必须请求成功(没有发送错误),服务器必须返回200HTTP状态值。或者,从1.8.1版本开始,301,302,303,307重定向状态码都可以。 要打开响应值的cache机制很简单: [ASIHTTPRequest setDefaultCache:[ASIDownloadCache sharedCache]]; 这样做以后,所有的request都会自动使用cache。如果你愿意,你可以让不同的request使用共享的cache: ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadCache:[ASIDownloadCache sharedCache]]; 你不会被局限于使用单一的cache,你可以想创建多少cache就创建多少cache,只要你喜欢 ^ ^。当你自己创建一个cache,你必须设定cache的路径——这路径必须是一个你拥有写权限的目录。 ASIDownloadCache *cache = [[[ASIDownloadCache alloc] init] autorelease]; [cache setStoragePath:@"/Users/ben/Documents/Cached-Downloads"]; //别忘了 - 你必须自己retaining你自己的cache! [self setMyCache:cache]; ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request setDownloadCache:[self myCache]]; cache策略cache策略是你控制cache中信息的主要方法,控制何时使用cache数据而非重新下载数据。 每个request的cache策略可是由request的cachePolicy 属性来控制的。cache策略使用掩码来定义,所以你可以二进制“与”操作他们。 // 每次都向服务器询问是否有新的内容可用,
// 如果请求失败, 使用cache的数据,即使这个数据已经过期了
[request setCachePolicy:ASIAskServerIfModifiedCachePolicy|ASIFallbackToCacheIfLoadFailsCachePolicy]; 你可以使用下列cache策略选项来控制request的缓存策略:
当你设定了一个cache对象的defaultCachePolicy 属性,所有使用这个cache对象的request都会使用这个cache策略,除非你为request设置了另外的策略。 存储策略存储策略允许你定义一个cache可以存储特定的相应数据多久。ASIHTTPRequest目前支持两种存储策略: ASICacheForSessionDurationCacheStoragePolicy是默认值。相应数据只会在会话期间被存储,在第一次使用cache时,或者在调用 [ASIHTTPRequest clearSession]时,数据会被清除。 使用ASICachePermanentlyCacheStoragePolicy,缓存的相应数据会被永久存储。要使用这个存储策略,向request设置: ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy]; 要手动清除cache,调用函数clearCachedResponsesForStoragePolicy:,传入要清除的cache数据的存储策略: [[ASIDownloadCache sharedCache] clearCachedResponsesForStoragePolicy:ASICachePermanentlyCacheStoragePolicy]; 其他cache相关的特性// 当你关闭 shouldRespectCacheControlHeaders,cache对象会存储响应数据,而无视
// 服务器的显式“请勿缓存”声明 (例如:cache-control 或者pragma: no-cache 头)
[[ASIDownloadCache sharedCache] setShouldRespectCacheControlHeaders:NO];
// 可以设定request的secondsToCache来覆盖服务器设定的内容有效期, 这时,响应数据
// 会一直被缓存,直到经过secondsToCache秒
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setSecondsToCache:60*60*24*30]; // 缓存30 天
//当request开始执行后,如果响应数据是从缓存中取得的,didUseCachedResponse 会返回YES
[request didUseCachedResponse];
// 向cache对象索取一个路径来存储相应数据. 这是使用download cache的最有效率的方法,
// 因为此时,当request完成后,数据不需要被复制到cache中.
[request setDownloadDestinationPath:
[[ASIDownloadCache sharedCache] pathToStoreCachedResponseDataForRequest:request]]; 编写自己的cache如果你已经持有一个download cache并且想将他插入ASIHTTPRequest中,或者你喜欢自己写自己的download cache,那么让你的cache实现ASICacheDelegate协议。
ASIHTTPRequest-流量控制从1.0.7版本开始,ASIHTTPRequest可以控制流量,使得所有request的流量不会超过用户定义的限制范围。这可以使得发送/接收大量数据的iphone程序更容易通过苹果的app store的审核。 流量是由一个全局的数量限制(字节)来控制的——每秒钟可以传送多少流量的数据。所有request共享这个限制。在发送或接收数据时,ASIHTTPRequest保持追踪上一秒所发送/接收的数据量。如果一个request达到了限制,其他正在执行的request将会等待。 在iOS上,你可以让ASIHTTPRequest在使用WWAN (GPRS/Edge/3G) 连接时自动打开流量控制,而当使用WiFi连接时自动关闭流量限制。 // 这将会对WWAN连接下的request进行流量控制(控制到预定义的值)
// Wi-Fi连接下的 request不会受影响
// 这个方法仅在iOS上可用
[ASIHTTPRequest setShouldThrottleBandwidthForWWAN:YES];
// 这将会对WWAN连接下的request进行流量控制(控制到自定义的值)
// 这个方法仅在iOS上可用
[ASIHTTPRequest throttleBandwidthForWWANUsingLimit:14800];
// 这将会控移动应用(mobile applications)的流量到预定义的值.
// 会限制所有requests, 不管request是不是WiFi连接下的 - 使用时要注意
[ASIHTTPRequest setMaxBandwidthPerSecond:ASIWWANBandwidthThrottleAmount];
// 记录每秒有多少字节的流量 (过去5秒内的平均值)
NSLog(@"%qi",[ASIHTTPRequest averageBandwidthUsedPerSecond]); IMPORTANT:在启用流量控制前,请参阅以下条目:
ASIHTTPRequest-客户端证书支持有时服务器要求提供客户端证书,从1.8版本开始,你可以随request发送证书。 // Will send the certificate attached to the identity (identity is a SecIdentityRef)
[request setClientCertificateIdentity:identity];
// Add an additional certificate (where cert is a SecCertificateRef)
[request setClientCertificates:[NSArray arrayWithObject:(id)cert]]; 在iPhone/iPad示例工程中的ClientCertificateTests.m中有一个很有用的函数用来从PKCS12数据创建SecIdentityRef (这个函数仅适用于iOS)。 ASIHTTPRequest-使用代理连接默认情况下,ASIHTTPRequest将尝试自动检测proxy设置。当然,你可以看自己手动设置: // 手动设置代理服务器
NSURL *url = [NSURL URLWithString:@"http://www.dreamingwish.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setProxyHost:@"192.168.0.1"];
[request setProxyPort:3128];
// 另一种方法, 使用代理配置脚本文件
// (最好使用本地pac文件)
[request setPACurl:[NSURL URLWithString:@"path/to/test.pac"]]; 要求授权的proxy在Mac OS上,ASIHTTPRequest可以自动检测到要求授权的proxy的凭据(前提是在系统设定中设置好)。在iOS上,ASIHTTPRequest则无法自动检测出授权凭据,所以你要么手动使用delegate来向你的controller或者用户索取合适的凭据,要么让ASIAuthenticationDialog向用户索取凭据。一旦获得了一个有效的proxy凭据,那么该凭据将被存储到keychian中(前提是启用useKeychainPersistence )并自动重用。 手动为proxy指定凭据NSURL *url = [NSURL URLWithString:@"http://www.dreamingwish.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setProxyHost:@"192.168.0.1"];
[request setProxyPort:3128];
//为要求授权的proxy设置username 和password
[request setProxyUsername:@"bencopsey"];
[request setProxyPassword:@"password"];
// 对于NTLM proxy,还要设置 domain (NTLM proxy功能是未经测试的)
[request setProxyDomain:@"la.la.land"]; 使用delegate来提供proxy凭据这个特性的工作原理和“使用delegate提供HTTP授权”一样,只有一点不同:你的delegate要响应proxyAuthenticationNeededForRequest:函数。 使用内建的授权对话框(仅适用于iOS)这个特性归功于1.0.8版本的新类ASIAuthenticationDialog 。用来向用户索取凭据来授权webserver或者proxy。 如果你的delegate不响应proxyAuthenticationNeededForRequest:函数,那么默认情况下,ASIHTTPRequest将会显示一个对客户来提示用户输入授权凭据。使用ASIHTTPRequest,开发者不再需要写额外的代码来显示授权对话框,因为默认情况下,ASIHTTPRequest就会显示它。 使用同步request时proxy授权对话框不会显示出来。 如果你不限使用proxy授权对话框,那么你要么实现proxyAuthenticationNeededForRequest:,要么设置shouldPresentProxyAuthenticationDialog 为false(此时你的程序将无法连接到proxy)。如果你要改变对话框的样式,你得继承ASIHTTPRequest类,重写showProxyAuthenticationDialog 来显示你自己的对话框或者ASIAuthenticationDialog 子类. ASIHTTPRequest-其他特性 设置user agent这样设置用户代理: [ASIHTTPRequest setDefaultUserAgentString:@"MyApp 1.0"] 如果不设置user agent,ASIHTTPRequest会为你创建一个。例如(Mac OS程序): My Application 1.0 (Macintosh; Mac OS X 10.5.7; en_GB) 你也可以为每个request设置user agent: [request setUserAgent:@"MyApp 1.0"] 当程序进入后台运行时,继续执行request(iOS)// iOS 4以上
[request setShouldContinueWhenAppEntersBackground:YES]; 监视网络活动//记录过去5秒的平均流量字节/秒
NSLog(@"%llu",[ASIHTTPRequest averageBandwidthUsedPerSecond]);
if ([ASIHTTPRequest isNetworkInUse]) {
// ASIHTTPRequest 进程中有requests正在使用网络
} 禁用自动更新网络连接标示符状态(iOS)默认情况下,ASIHTTPRequest在request使用网络连接时,会自动显示网络连接标示符(iOS状态条中)。如果你想自己控制标示符,你可以禁用这个特性: [ASIHTTPRequest setShouldUpdateNetworkActivityIndicator:NO]; 超时自动重试设置超时自动重试最大次数为2: [request setNumberOfTimesToRetryOnTimeout:2]; 设置持久连接默认情况下,ASIHTTPRequest将会尝试保持对一个服务器的连接以便往后的连接到该服务器的request可以重用这个连接(这个特性可以显著地提高速度,尤其是当你会要进行很多小数据量request时)。当连接到HTTP 1.1服务器或者服务器发送keep-alive头时,持久连接会自动被使用。当服务器显式地发送”Connection:close”头时,持久连接就不会被使用。另外,默认情况下,ASIHTTPRequest不会对包含请求体(例如POST/PUT)的request使用持久连接(从1.8.1版本开始)。通过设置request,你可以强制让此类request使用持久连接: [request setRequestMethod:@"PUT"];
[request setShouldAttemptPersistentConnection:YES]; 很多服务器不会在响应头中规定持久连接的持久时间,它们可能会在任何一个request完成时候关闭连接。如果一个服务器没有规定持久连接的持久时间,ASIHTTPRequest将会在一个request完成后,保持连接60秒。对于你的服务器设置来时,60可能很长,也可能很短。 如果这个超时时间太长,那么可能一个request使用这个连接时,服务器可能已经关闭了这个连接。当ASIHTTPRequest遇到连接已关闭错误,它就会在一个新的连接上重试这个request。 如果这个超时时间太短,而服务器却更想让这个连接保持更长时间,但是ASIHTTPRequest又开启了不必要的新连接,那么这将导致效率降低。 // 设置持久连接的超时时间为120秒
[request setPersistentConnectionTimeoutSeconds:120];
// 彻底禁用持久连接
[request setShouldAttemptPersistentConnection:NO]; 强制使用HTTP 1.0[request setUseHTTPVersionOne:YES]; 禁用安全证书校验如果你有一个自签名的证书,你可能想禁用证书校验来做测试。这里我建议你从一个可信的CA购买证书,并为生产(production)期的app(梦维:app还有测试期等等阶段不是?)启用证书校验。 [request setValidatesSecureCertificate:NO]; ASIHTTPRequest-Debug选项ASIHTTPRequest提供少量的有助于调试request行为的宏标记。这些宏可以从ASIHTTPRequestConfig.h文件中找到。 当打开这些标志时,request将会打印一些信息到控制台,显示它们正在做什么。 DEBUG_REQUEST_STATUS打印request的生命周期的所有信息,开始,结束上载,结束下载。 DEBUG_THROTTLING打印request使用了多少流量(大致),如果request的流量被控制,打印如何被控制。当与DEBUG_REQUEST_STATUS结合使用时,这一项可以用来调试“超时”,你可以看到request停止发送或接收数据的时间点。 DEBUG_PERSISTENT_CONNECTIONS打印request如何重用持久连接的信息,如果你看到这样的信息: Request attempted to use connection #1, but it has been closed – will retry with a new connection 这说明你设置的persistentConnectionTimeoutSeconds 太大了。 DEBUG_HTTP_AUTHENTICATION1.8.1版本的新特性:开启这一项会打印request如何处理HTTP授权(Basic,Digest或者NTLM)的相关信息。 DEBUG_FORM_DATA_REQUEST打印出ASIFormDataRequest将发送的整个request体。使用ASIFormDataRequest时,这一项很有用。
由于正式版的iOS5出来了,所以我也试着去升级了。于是下载了最新的Xcode,才1.7G左右,比以往的安装包要小许多。 升级Xcode后,打开以前创建的工程, 运气好,一个错误都没有,程序也能正常跑起来。由于我程序中用了ASIHttpRequest这个库,让我发现了一个小问题,就是 ASIAuthenticationDialog这个内置对话框在网络有代理的情况下出现,然后无论点cancle或是login都不能dismiss。在4.3的SDK中完全没问题,在5.0的SDK中就会在Console中看到输出: Unbalanced calls to begin/end appearance transitions for <ASIAutorotatingViewController:> 很明显示在sdk5中, 用这个库有问题,还有在停止调式的时候,程序会有异常产生。
于是很明显示是SDK5的变化影响了ASIHttpRequest的正常使用。于是我要fix这个问题,经过我研究发现,dismiss不起作用是由于UIViewController的parentViewController不再返回正确值了,返回的是nil,而在SDK5中被presentingViewController取代了。于是在ASIAuthenticationDialog.m中找到+(void)dismiss这个方法并修改为:
这样编译出来的程序能在ios5设备上正确运行,但是在ios5以下的设备则会crash。因为是库,所以要考虑到兼容不同版本,于是进一步修改为:
还有上面那个Console的错误提示,解决方法是,在ASIAuthenticationDialog.m中找到-(void)show这个方法,并把最后一行代码
修改为:
这下就可以正常运行了哟, 我的问题也解决了。关于ASIHttpRequest的其它方面,到目前为止还没发现问题。 |
|
最新评论