iOS开发 - HTTP终结者 "ASI"

ASI

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

ASI的github地址
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

发送同步请求

 #import "ASIHTTPRequest.h"
// 1.创建请求
NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/Server/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)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data

//请求失败就调用
- (void)requestFailed:(ASIHTTPRequest *)request

//请求成功完毕就调用
- (void)requestFinished:(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;

typedef void (^ASIBasicBlock)(void);
typedef void (^ASIHeadersBlock)(NSDictionary *responseHeaders);
typedef void (^ASISizeBlock)(long long size);
typedef void (^ASIProgressBlock)(unsigned long long size, unsigned long long total);
typedef void (^ASIDataBlock)(NSData *data);

获得服务器的响应

//获得状态码\状态信息
@property (atomic, assign,readonly) int responseStatusCode;
@property (atomic, retain,readonly) NSString *responseStatusMessage;

//获得响应头
@property (atomic, retain) NSDictionary *responseHeaders;

//获得实体内容(响应体)
- (NSData *)responseData;
- (NSString *)responseString;

发送POST请求

包含头文件:#import "ASIFormDataRequest.h"
// 1.创建请求
NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/Server/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 *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *filepath = [caches stringByAppendingPathComponent:@"test.mp4"];
request.downloadDestinationPath = filepath;
// 设置下载代理
request.downloadProgressDelegate = self.progressView;

大文件支持断点续传
// 设置文件的临时路径
request.temporaryFileDownloadPath = tmpFilepath;
// 设置支持断点续传
request.allowResumeForFileDownloads = 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

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

//新本地缓存
ASIUseDefaultCachePolicy
ASIAskServerIfModifiedWhenStaleCachePolicy

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

不读取缓存数据
//ASIDoNotReadFromCacheCachePolicy

//不缓存数据,不写缓存
ASIDoNotWriteToCacheCachePolicy

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

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

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

缓存某个请求

// 设置缓存策略
ASIDownloadCache *cache = [ASIDownloadCache sharedCache];
[cache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy | ASIFallbackToCacheIfLoadFailsCachePolicy];
// 使用缓存
[request setDownloadCache:cache];
// 设置缓存的存储策略(永久存储)
[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];


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

其他用法

现在是否有网络请求在处理中
[ASIHTTPRequest isNetworkInUse];

当正在请求时,是否要在状态栏显示联网状态(转圈圈)
[ASIHTTPRequest setShouldUpdateNetworkActivityIndicator:YES];

当应用后台运行时,是否仍然继续处理网络请求
request.shouldContinueWhenAppEntersBackground = YES;

设置请求超时后重试的次数
request.numberOfTimesToRetryOnTimeout = 2; // 重试2次

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。