您的位置:首页 > 理论基础 > 计算机网络

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

2015-03-01 11:27 513 查看
全称是ASIHTTPRequest,外号“HTTP终结者”,功能十分强大

基于底层的CFNetwork框架,运行效率很高

可惜作者早已停止更新,有一些潜在的BUG无人去解决

很多公司的旧项目里面都残留着它的身影,以前的很多iOS项目都是ASI + SBJson

会不会用ASI,可以算是检验是否为老牌iOS程序员的标准之一

ASI的github地址

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

ASI的使用参考

/article/4940343.html

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

配置 – 导入源码



配置 – 添加依赖类库



发送同步请求

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


发送异步请求

// 1.创建请求
NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/MJServer/login?username=123&pwd=123"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
request.timeOutSeconds = 5; // 超时

// 2.设置代理
request.delegate = self;

// 3.发送异步请求
[request startAsynchronous];

// ASI通过代理的方式处理异步请求,请求成功、失败都会通知代理
//   代理需要遵守ASIHTTPRequestDelegate协议


ASIHTTPRequestDelegate

请求开始就调用

- (void)requestStarted:(ASIHTTPRequest *)request


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

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


请求成功完毕就调用

- (void)requestFinished:(ASIHTTPRequest *)request


请求失败就调用

- (void)requestFailed:(ASIHTTPRequest *)request


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

[request clearDelegatesAndCancel];


ASI的SEL回调

@property (atomic, assign) SEL didStartSelector;
@property (atomic, assign) SEL didReceiveResponseHeadersSelector;
@property (atomic, assign) SEL willRedirectSelector;
@property (atomic, assign) SEL didFinishSelector;
@property (atomic, assign) SEL didFailSelector;
@property (atomic, assign) SEL didReceiveDataSelector;


ASI的block回调

- (void)setStartedBlock:(ASIBasicBlock)aStartedBlock;
- (void)setHeadersReceivedBlock:(ASIHeadersBlock)aReceivedBlock;
- (void)setCompletionBlock:(ASIBasicBlock)aCompletionBlock;
- (void)setFailedBlock:(ASIBasicBlock)aFailedBlock;
- (void)setBytesReceivedBlock:(ASIProgressBlock)aBytesReceivedBlock;
- (void)setBytesSentBlock:(ASIProgressBlock)aBytesSentBlock;
- (void)setDownloadSizeIncrementedBlock:(ASISizeBlock) aDownloadSizeIncrementedBlock;
- (void)setUploadSizeIncrementedBlock:(ASISizeBlock) anUploadSizeIncrementedBlock;
- (void)setDataReceivedBlock:(ASIDataBlock)aReceivedBlock;
- (void)setAuthenticationNeededBlock:(ASIBasicBlock)anAuthenticationBlock;
- (void)setProxyAuthenticationNeededBlock:(ASIBasicBlock)aProxyAuthenticationBlock;
- (void)setRequestRedirectedBlock:(ASIBasicBlock)aRedirectBlock;


获得服务器的响应

获得状态码\状态信息

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


获得响应头

@property (atomic, retain) NSDictionary *responseHeaders;


获得实体内容(响应体)

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


发送普通的POST请求 – 方法1

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


发送普通的POST请求 – 方法2

包含头文件:#import "ASIFormDataRequest.h"
// 1.创建请求
NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/MJServer/login"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

// 2.设置请求参数
[request addPostValue:@"123" forKey:@"username"];
[request addPostValue:@"123" forKey:@"pwd"];
// 注意addPostValue和setPostValue的区别


文件上传

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


文件上传 – 添加文件参数

有2种添加文件参数的方法
通过文件的全路径
- (void)addFile:(NSString *)filePath forKey:(NSString *)key
- (void)addFile:(NSString *)filePath withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key

通过文件的具体数据
- (void)addData:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key


文件下载

// 设置缓存路径
NSString *tmp = NSTemporaryDirectory();
request.downloadDestinationPath = [tmp stringByAppendingPathComponent:@"tools.zip"];
// 设置下载代理
request.downloadProgressDelegate = self.progressView;

大文件支持断点续传
[request setAllowResumeForFileDownloads:YES];


监听文件上传\下载进度

成为ASI的代理
- (void)setUploadProgressDelegate:(id)newDelegate

遵守ASIProgressDelegate协议,实现协议方法
- (void)setProgress:(float)newProgress;


缓存

ASI也提供了数据缓存功能

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

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

使用ASIDownloadCache类管理缓存

常见ASIDownloadCache用法
取得默认的缓存对象
ASIDownloadCache *cache = [ASIDownloadCache sharedCache];

设置缓存策略
- (void)setDefaultCachePolicy:(ASICachePolicy)cachePolicy

设置缓存路径
- (void)setStoragePath:(NSString *)path


缓存策略 - ASICachePolicy

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

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

ASIUseDefaultCachePolicy

ASIAskServerIfModifiedWhenStaleCachePolicy

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

ASIAskServerIfModifiedCachePolicy

不读取缓存数据

ASIDoNotReadFromCacheCachePolicy

不缓存数据,不写缓存

ASIDoNotWriteToCacheCachePolicy

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

ASIOnlyLoadIfNotCachedCachePolicy

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

ASIDontLoadCachePolicy

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

ASIFallbackToCacheIfLoadFailsCachePolicy

缓存某个请求

// 设置缓存策略

ASIDownloadCache *cache = [ASIDownloadCache sharedCache];

[cache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy | ASIFallbackToCacheIfLoadFailsCachePolicy];

// 使用缓存

[request setDownloadCache:cache];

// 设置缓存的存储策略(永久存储)

[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];


ASIHTTPRequest缓存的存储策略

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

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

ASICacheForSessionDurationCacheStoragePolicy

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

ASICachePermanentlyCacheStoragePolicy

缓存所有请求

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


缓存的其他特性

设置缓存的有效期
[request setSecondsToCache:60 * 60 * 24 * 7]; // 缓存7天

判断数据是否从缓存读取的
BOOL useCache = [request didUseCachedResponse];


ASIHTTPRequest

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

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

可以设置请求之间的依赖

… …

ASIFormDataRequest继承自ASIHTTPRequest

其他用法

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

[ASIHTTPRequest isNetworkInUse];


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

[ASIHTTPRequest setShouldUpdateNetworkActivityIndicator:YES];


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

request.shouldContinueWhenAppEntersBackground = YES;


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

request.numberOfTimesToRetryOnTimeout = 2; // 重试2次
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: