iOS开发之网络请求(一)ASIHTTPRequest

  • 全称是ASIHTTPRequest,外号“HTTP终结者,功能十分强大
  • 基于底层的CFNetwork框架,运行效率很高
  • 可惜作者早已停止更新,有一些潜在的BUG无人去解决
  • 很多公司的旧项目里面都残留着它的身影,以前的很多iOS项目都是ASI + SBJson
  • 会不会用ASI,可以算是检验是否为老牌iOS程序员的标准之一

ASIgithub地址

https://github.com/pokeb/asi-http-request

 

ASI的使用参考

http://www.cnblogs.com/dotey/archive/2011/05/10/2041966.html

http://www.oschina.net/question/54100_36184

配置 导入源码

 

配置 添加依赖类库

 

发送同步请求

 1 包含主文件  #import "ASIHTTPRequest.h"
 2 // 1.创建请求
 3 NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/MJServer/login?username=123&pwd=123"];
 4 ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
 5 request.timeOutSeconds = 5; // 超时
 6 // 2.发送同步请求
 7 [request startSynchronous];
 8 // 3.获得错误信息
 9 NSError *error = [request error];
10 if (error) {
11     NSLog(@"出错了");
12 } else {
13     // 获得服务器的响应
14         NSData *data = [request responseData];
15 } // [request responseData]

发送异步请求

 1 // 1.创建请求
 2 NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/MJServer/login?username=123&pwd=123"];
 3 ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
 4 request.timeOutSeconds = 5; // 超时
 5 
 6 // 2.设置代理
 7 request.delegate = self;
 8 
 9 // 3.发送异步请求
10 [request startAsynchronous];
11 
12 // ASI通过代理的方式处理异步请求,请求成功、失败都会通知代理
13 //   代理需要遵守ASIHTTPRequestDelegate协议

ASIHTTPRequestDelegate

请求开始就调用

1 - (void)requestStarted:(ASIHTTPRequest *)request

接收到服务器的数据就调用

1 - (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data

请求成功完毕就调用

1 - (void)requestFinished:(ASIHTTPRequest *)request

请求失败就调用

1 - (void)requestFailed:(ASIHTTPRequest *)request

注意:应当在控制器被销毁的时候,取消请求

1 [request clearDelegatesAndCancel];

ASISEL回调

1 @property (atomic, assign) SEL didStartSelector;
2 @property (atomic, assign) SEL didReceiveResponseHeadersSelector;
3 @property (atomic, assign) SEL willRedirectSelector;
4 @property (atomic, assign) SEL didFinishSelector;
5 @property (atomic, assign) SEL didFailSelector;
6 @property (atomic, assign) SEL didReceiveDataSelector;

ASIblock回调

 1 - (void)setStartedBlock:(ASIBasicBlock)aStartedBlock;
 2 - (void)setHeadersReceivedBlock:(ASIHeadersBlock)aReceivedBlock;
 3 - (void)setCompletionBlock:(ASIBasicBlock)aCompletionBlock;
 4 - (void)setFailedBlock:(ASIBasicBlock)aFailedBlock;
 5 - (void)setBytesReceivedBlock:(ASIProgressBlock)aBytesReceivedBlock;
 6 - (void)setBytesSentBlock:(ASIProgressBlock)aBytesSentBlock;
 7 - (void)setDownloadSizeIncrementedBlock:(ASISizeBlock) aDownloadSizeIncrementedBlock;
 8 - (void)setUploadSizeIncrementedBlock:(ASISizeBlock) anUploadSizeIncrementedBlock;
 9 - (void)setDataReceivedBlock:(ASIDataBlock)aReceivedBlock;
10 - (void)setAuthenticationNeededBlock:(ASIBasicBlock)anAuthenticationBlock;
11 - (void)setProxyAuthenticationNeededBlock:(ASIBasicBlock)aProxyAuthenticationBlock;
12 - (void)setRequestRedirectedBlock:(ASIBasicBlock)aRedirectBlock;

获得服务器的响应

获得状态码\状态信息

1 @property (atomic, assign,readonly) int responseStatusCode;
2 @property (atomic, retain,readonly) NSString *responseStatusMessage;

获得响应头

1 @property (atomic, retain) NSDictionary *responseHeaders;

获得实体内容(响应体)

1 - (NSData *)responseData;
2 - (NSString *)responseString;

发送普通的POST请求方法1

 1 // 创建请求
 2 NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/MJServer/login"];
 3 ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
 4 // 超时
 5 request.timeOutSeconds = 5; 
 6 // 请求方法
 7 request.requestMethod = @"POST"; 
 8 // 拼接请求体
 9 NSData *data = [@"username=123&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];
10 [request appendPostData:data];

发送普通的POST请求方法2

1 包含头文件:#import "ASIFormDataRequest.h"
2 // 1.创建请求
3 NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/MJServer/login"];
4 ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
5 
6 // 2.设置请求参数
7 [request addPostValue:@"123" forKey:@"username"];
8 [request addPostValue:@"123" forKey:@"pwd"];
9 // 注意addPostValue和setPostValue的区别

文件上传

 1 ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
 2 // 添加普通的请求参数
 3 [request addPostValue:@"MJ" forKey:@"username"];
 4 // 添加文件参数
 5 NSString *file = [[NSBundle mainBundle] pathForResource:@"musicplayer.png" ofType:nil];
 6 [request addFile:file forKey:@"file"];
 7 // 或者
 8 UIImage *image = [UIImage imageNamed:@"musicplayer"];
 9 NSData *data = UIImagePNGRepresentation(image);
10 [request addData:data withFileName:@"test.png" andContentType:@"image/png" forKey:@"file"];

文件上传添加文件参数

1 有2种添加文件参数的方法
2 通过文件的全路径
3 - (void)addFile:(NSString *)filePath forKey:(NSString *)key
4 - (void)addFile:(NSString *)filePath withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key
5 
6 通过文件的具体数据
7 - (void)addData:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key

文件下载

1 // 设置缓存路径
2 NSString *tmp = NSTemporaryDirectory();
3 request.downloadDestinationPath = [tmp stringByAppendingPathComponent:@"tools.zip"];
4 // 设置下载代理
5 request.downloadProgressDelegate = self.progressView;
6 
7 大文件支持断点续传
8 [request setAllowResumeForFileDownloads:YES];

监听文件上传\下载进度

1 成为ASI的代理
2 - (void)setUploadProgressDelegate:(id)newDelegate
3 
4 遵守ASIProgressDelegate协议,实现协议方法
5 - (void)setProgress:(float)newProgress;

缓存

ASI也提供了数据缓存功能

它只对Get请求的响应数据进行缓存

被缓存的数据必需是成功的200请求

使用ASIDownloadCache类管理缓存

1 常见ASIDownloadCache用法
2 取得默认的缓存对象
3 ASIDownloadCache *cache = [ASIDownloadCache sharedCache];
4 
5 设置缓存策略
6 - (void)setDefaultCachePolicy:(ASICachePolicy)cachePolicy
7 
8 设置缓存路径
9 - (void)setStoragePath:(NSString *)path

缓存策略 - ASICachePolicy

缓存策略:什么时候进行缓存,缓存数据的利用方式。可用组合使用

默认缓存策略:如果存在未过期的缓存数据,则使用缓存;否则进行网络请求,判断服务器版本与本地版本是否一样,如果一样,则使用缓存。如果服务器有新版本,会进行网络请求,并更新本地缓存

ASIUseDefaultCachePolicy

ASIAskServerIfModifiedWhenStaleCachePolicy

与默认缓存大致一样,区别仅是每次请求都会 去服务器判断是否有更新

ASIAskServerIfModifiedCachePolicy

不读取缓存数据

ASIDoNotReadFromCacheCachePolicy

不缓存数据,不写缓存

ASIDoNotWriteToCacheCachePolicy

如果有缓存,不管其过期与否,总会拿来使用,没有缓存就重新请求

ASIOnlyLoadIfNotCachedCachePolicy

有缓存,拿来使用,如果没有缓存,请求将被取消(没有错误信息)

ASIDontLoadCachePolicy

请求失败时,如果有缓存则返回缓存(经常被用来与其它选项组合使用)

ASIFallbackToCacheIfLoadFailsCachePolicy

缓存某个请求

 1 // 设置缓存策略
 2 
 3 ASIDownloadCache *cache = [ASIDownloadCache sharedCache];
 4 
 5 [cache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy | ASIFallbackToCacheIfLoadFailsCachePolicy];
 6 
 7 // 使用缓存
 8 
 9 [request setDownloadCache:cache];
10 
11 // 设置缓存的存储策略(永久存储)
12 
13 [request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];

 

ASIHTTPRequest缓存的存储策略

缓存的存储策略:缓存需要保存多长时间

默认策略,基于session的缓存数据存储,当下次运行或[ASIHTTPRequest clearSession]时,缓存将失效(内存缓存

ASICacheForSessionDurationCacheStoragePolicy

 

缓存数据永久保存在本地(硬盘缓存

ASICachePermanentlyCacheStoragePolicy

缓存所有请求

1 // 设置缓存策略
2 ASIDownloadCache *cache = [ASIDownloadCache sharedCache];
3 [cache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy | ASIFallbackToCacheIfLoadFailsCachePolicy];
4 // 使用缓存
5 [ASIHTTPRequest setDefaultCache:cache];

缓存的其他特性

1 设置缓存的有效期
2 [request setSecondsToCache:60 * 60 * 24 * 7]; // 缓存7天
3 
4 判断数据是否从缓存读取的
5 BOOL useCache = [request didUseCachedResponse];

ASIHTTPRequest

实际上ASIHTTPRequest继承自NSOperation,意味着

可以将多个ASIHTTPRequest放到NSOperationQueue中,同时管理多个请求

可以设置请求之间的依赖

… …

 

ASIFormDataRequest继承自ASIHTTPRequest

其他用法

现在是否有网络请求在处理中

1 [ASIHTTPRequest isNetworkInUse];

 

当正在请求时,是否要在状态栏显示联网状态(转圈圈)

1 [ASIHTTPRequest setShouldUpdateNetworkActivityIndicator:YES];

 

当应用后台运行时,是否仍然继续处理网络请求

1 request.shouldContinueWhenAppEntersBackground = YES;

 

设置请求超时后重试的次数

1 request.numberOfTimesToRetryOnTimeout = 2; // 重试2次

 

posted @ 2015-03-01 11:27  董文博  阅读(3303)  评论(0编辑  收藏  举报