Quantcast
Channel: CSDN博客移动开发推荐文章
Viewing all articles
Browse latest Browse all 5930

25、26、27day-ASI

$
0
0

二、ASI

全称是ASIHTTPRequest,外号“HTTP终结者”,功能十分强大.基于底层的CFNetwork框架,运行效率很高;可惜作者早已停止更新,有一些潜在的BUG无人去解决--Please note that I am no longer working on this library - you may want to consider using something else for new projects. :)
很多公司的旧项目里面都残留着它的身影,以前的很多iOS项目都是ASI + SBJson
1、ASI的github地址
ASI的使用参考http://www.oschina.net/question/54100_36184
ps: 添加依赖的动态库 libz.tbd

2、发送同步请求

request.timeOutSeconds = 5; // 超时
// 2.发送同步请求
[request startSynchronous];
// 3.获得错误信息
NSError *error = [request error];
if (error) {
NSLog(@"出错了");
} else {
//获得服务器的响应
    NSData *data = [request responseData];
} //
[request responseData]

3、发送异步请求

request.timeOutSeconds = 5; // 超时
// 2.设置代理
request.delegate = self;
// 3.发送异步请求
[request startAsynchronous];
// ASI通过代理的方式处理异步请求,请求成功、失败都会通知代理
//   代理需要遵守ASIHTTPRequestDelegate协议

4、@protocol ASIHTTPRequestDelegate

// These are the default delegate methods for request status

// You can use different ones by setting didStartSelector / didFinishSelector / didFailSelector
- (void)requestStarted:(ASIHTTPRequest *)request;
- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders;
- (void)request:(ASIHTTPRequest *)request willRedirectToURL:(NSURL *)newURL;
- (void)requestFinished:(ASIHTTPRequest *)request;//请求成功完毕就调用
- (void)requestFailed:(ASIHTTPRequest *)request;//请求失败调用
- (void)requestRedirected:(ASIHTTPRequest *)request;

// When a delegate implements this method, it is expected to process all incoming data itself
// This means that responseData / responseString / downloadDestinationPath etc are ignored
// You can have the request call a different method by setting didReceiveDataSelector接受到服务器的数据就调用
- (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data;

// If a delegate implements one of these, it will be asked to supply credentials when none are available
// The delegate can then either restart the request ([request retryUsingSuppliedCredentials]) once credentials have been set
// or cancel it ([request cancelAuthentication])
- (void)authenticationNeededForRequest:(ASIHTTPRequest *)request;
- (void)proxyAuthenticationNeededForRequest:(ASIHTTPRequest *)request;

//ps:安全的内存回收建议
// Clears all delegates and blocks, then cancels the request
- (void)clearDelegatesAndCancel;
//request并没有retain你的delegate,所以在没有请求完的时候释放了此delegate,需要在dealloc方法里先取消所有请求,再释放请求实例
 //eg.
   self.delegate = delegate;
   self.request.delegate = self;
- (void)requestFinished:(ASIHTTPRequest *)request{
   [self.delegate requestFinished:request];
}
- (void)requestFailed:(ASIHTTPRequest *)request{
   [self.delegate requestFailed:request];
}

5、ASI 的sel 回调(调用:通知、代理)

@property (assign) SEL didStartSelector;
@property (assign) SEL didReceiveResponseHeadersSelector;
@property (assign) SEL willRedirectSelector;
@property (assign) SEL didFinishSelector;
@property (assign) SEL didFailSelector;
@property (assign) SEL didReceiveDataSelector;
  //eg.
   self.request.didFinishSelector = @selector(requestFinished:);
   self.request.didFailSelector = @selector(requestFailed:);

6、ASI的BLOCK 回调(执行)

#if NS_BLOCKS_AVAILABLE
- (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;
#endif
#if NS_BLOCKS_AVAILABLE
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);
#endif

7、获取服务的响应数据

/获得状态码\状态信息
@property (atomic, assign,readonly) int responseStatusCode;
@property (atomic, retain,readonly) NSString *responseStatusMessage;
//获得响应头
@property (atomic, retain) NSDictionary *responseHeaders;
//获得实体内容(响应体)
- (NSData *)responseData;
- (NSString *)responseString;
*********eg.*******
NSString * strResponse = [[NSString alloc] initWithData:request.responseData encoding:NSUTF8StringEncoding];
    NSLog(@"requestFinished");
    NSLog(@"statusCode: %i", [request responseStatusCode]);
    NSLog(@"statusMessage: %@", [request responseStatusMessage]);
    NSLog(@"response:\n%@", strResponse);

8、发送post请求

typedef enum _ASIPostFormat {
    ASIMultipartFormDataPostFormat = 0,
    ASIURLEncodedPostFormat = 1
} ASIPostFormat;
@interface ASIFormDataRequest : ASIHTTPRequest <NSCopying> {
    // Parameters that will be POSTed to the url
    NSMutableArray *postData;  
    // Files that will be POSTed to the url
    NSMutableArray *fileData;
    ASIPostFormat postFormat;
    NSStringEncoding stringEncoding;



#if DEBUG_FORM_DATA_REQUEST
    // Will store a string version of the request body that will be printed to the console when ASIHTTPREQUEST_DEBUG is set in GCC_PREPROCESSOR_DEFINITIONS
    NSString *debugBodyString;
#endif
}
#pragma mark utilities
- (NSString*)encodeURL:(NSString *)string;



#pragma mark setup request
// Add a POST variable to the request  普通的请求参数
- (void)addPostValue:(id <NSObject>)value forKey:(NSString *)key;
// Set a POST variable for this request, clearing any others with the same key
- (void)setPostValue:(id <NSObject>)value forKey:(NSString *)key;




// Add the contents of a local file to the request 添加文件的全路径参数
- (void)addFile:(NSString *)filePath forKey:(NSString *)key;
// Same as above, but you can specify the content-type and file name
- (void)addFile:(NSString *)filePath withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key;
// Add the contents of a local file to the request, clearing any others with the same key
- (void)setFile:(NSString *)filePath forKey:(NSString *)key;
// Same as above, but you can specify the content-type and file name
- (void)setFile:(NSString *)filePath withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key;
/*
eg. 文件上传
NSString *file = [[NSBundle mainBundle] pathForResource:@"musicplayer.png" ofType:nil];
[request addFile:file forKey:@"file"];

*/

// Add the contents of an NSData object to the request 添加文件的具体数据参数
- (void)addData:(NSData *)data forKey:(NSString *)key;
// Same as above, but you can specify the content-type and file name
- (void)addData:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key;
// Add the contents of an NSData object to the request, clearing any others with the same key
- (void)setData:(NSData *)data forKey:(NSString *)key;
// Same as above, but you can specify the content-type and file name
- (void)setData:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key;
/*
UIImage *image = [UIImage imageNamed:@"musicplayer"];
NSData *data = UIImagePNGRepresentation(image);
[request addData:data withFileName:@"test.png" andContentType:@"image/png" forKey:@"file"];

*/

@property (assign) ASIPostFormat postFormat;
@property (assign) NSStringEncoding stringEncoding;


**********************  ASIHTTPRequest***********
ps:@interface ASIHTTPRequest : NSOperation <NSCopying>
实际上ASIHTTPRequest继承自NSOperation,意味着
可以将多个ASIHTTPRequest放到NSOperationQueue中,同时管理多个请求
可以设置请求之间的依赖.

+ (BOOL)isNetworkInUse;//现在是否有网络请求在处理中
+ (void)setShouldUpdateNetworkActivityIndicator:(BOOL)shouldUpdate;//当正在请求时,是否要在状态栏显示联网状态

@property (assign) BOOL shouldContinueWhenAppEntersBackground;//当应用进入后台运行时,是否继续处理网络请求
/ Set to allow a request to automatically retry itself on timeout
    // Default is zero - timeout will stop the request
    int numberOfTimesToRetryOnTimeout;

9、文件下载

// 设置缓存路径
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;

10、缓存

它只对Get请求的响应数据进行缓存;被缓存的数据必需是成功的200请求;使用ASIDownloadCache类管理缓存
1)ASIDownloadCache

// Returns a static instance of an ASIDownloadCache
// In most circumstances, it will make sense to use this as a global cache, rather than creating your own cache
// To make ASIHTTPRequests use it automatically, use [ASIHTTPRequest setDefaultCache:[ASIDownloadCache sharedCache]];
+ (id)sharedCache;
@property (retain, nonatomic) NSString *storagePath;//缓存路径
----------缓存策略 - ASICachePolicy--  什么时候进行缓存,缓存数据的利用方式;可用组合使用----------
typedef enum _ASICachePolicy {

    // The default cache policy. When you set a request to use this, it will use the cache's defaultCachePolicy
    // ASIDownloadCache's default cache policy is 'ASIAskServerIfModifiedWhenStaleCachePolicy'
    ASIUseDefaultCachePolicy = 0,
    // Tell the request not to read from the cache
    ASIDoNotReadFromCacheCachePolicy = 1,


    // The the request not to write to the cache
    ASIDoNotWriteToCacheCachePolicy = 2,


    // Ask the server if there is an updated version of this resource (using a conditional GET) ONLY when the cached data is stale
    ASIAskServerIfModifiedWhenStaleCachePolicy = 4,




    // Always ask the server if there is an updated version of this resource (using a conditional GET)
    ASIAskServerIfModifiedCachePolicy = 8,


    // If cached data exists, use it even if it is stale. This means requests will not talk to the server unless the resource they are requesting is not in the cache
    ASIOnlyLoadIfNotCachedCachePolicy = 16,


    // If cached data exists, use it even if it is stale. If cached data does not exist, stop (will not set an error on the request)
    ASIDontLoadCachePolicy = 32,




    // Specifies that cached data may be used if the request fails. If cached data is used, the request will succeed without error. Usually used in combination with other options above.
    ASIFallbackToCacheIfLoadFailsCachePolicy = 64
} ASICachePolicy;

-----------------------------例子:缓存某个请求--------
// 设置缓存策略
ASIDownloadCache *cache = [ASIDownloadCache sharedCache];
[cache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy | ASIFallbackToCacheIfLoadFailsCachePolicy];


// 使用缓存
[request setDownloadCache:cache];

// 设置缓存的存储策略(永久存储)
[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy]
/*******存储策略***/
// Cache storage policies control whether cached data persists between application launches (ASICachePermanentlyCacheStoragePolicy) or not (ASICacheForSessionDurationCacheStoragePolicy)
// Calling [ASIHTTPRequest clearSession] will remove any data stored using ASICacheForSessionDurationCacheStoragePolicy
typedef enum _ASICacheStoragePolicy {
    ASICacheForSessionDurationCacheStoragePolicy = 0,
    ASICachePermanentlyCacheStoragePolicy = 1
} ASICacheStoragePolicy;

p s:缓存的其它特性
//设置缓存的有效期
[request setSecondsToCache:60 * 60 * 24 * 7]; // 缓存7天
//判断数据是否从缓存读取的
BOOL useCache =[request didUseCachedResponse];

ASI的文件下载,断点续传

- (void)download{
    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1:8080/MJServer/resources/videos/iPhoneSimulator6.1.sdk.zip"];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    //设置文件的缓存路径
    NSString *tmp = NSTemporaryDirectory();
    NSString *filepath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    NSLog(@"%@,--%@",tmp,filepath);
    [request setDownloadDestinationPath:[filepath stringByAppendingPathComponent:@"iPhoneSimulator6.1.sdk.zip"]];
    // //大文件支持断点续传 同时设置setTemporaryFileDownloadPath、setAllowResumeForFileDownloads
    [request setTemporaryFileDownloadPath:[tmp stringByAppendingPathComponent:@"test.zip"]];
[request setAllowResumeForFileDownloads:YES];


    [request setTimeOutSeconds:15];
    [request setDownloadProgressDelegate:self];
    [request setDelegate:self];
    [request startSynchronous];
    NSError *error = request.error;
    if (error) {
        NSLog(@"%s--请求失败",__func__);
        return;
    }
    NSLog(@"%s,%@",__func__,request.responseData);//实现了ASIHTTPRequestDelegate的代理方法didReceiveData,  responseData / responseString / downloadDestinationPath将返回为空
}
作者:u011018979 发表于2017/7/10 15:17:26 原文链接
阅读:19 评论:0 查看评论

Viewing all articles
Browse latest Browse all 5930

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>