ASIHTTPRequest是第三方类库,ASIHTTPRequest对CFNetwork API进行了封装。
有如下特点:
第一、同步请求:
ASIHTTPRequest *httpRequest=[ASIHTTPRequest requestWithURL:url];
[httpRequest setRequestMethod:@"GET"];
[httpRequest setTimeOutSeconds:60];
[httpRequest startSynchronous];
NSError *error=httpRequest.error;
if(error==nil)
{
NSData *data=httpRequest.responseData;
UIImage *image=[UIImage imageWithData:data];
self.image=image;
}else
{
NSLog(@"请求网络错误");
}
第二、异步请求:
用delegate实现:
-(void)asynchronous:(NSURL*)url
{
ASIHTTPRequest *httpRequest=[ASIHTTPRequest requestWithURL:url];
[httpRequest setRequestMethod:@"GET"];
[httpRequest setTimeOutSeconds:60];
httpRequest.delegate=self;
[httpRequest startAsynchronous];
}
#pragma mark - ASIHTTPRequest delegate
- (void)requestFinished:(ASIHTTPRequest *)request
{
UIImage *image=[UIImage imageWithData:request.responseData];
self.image=image;
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error=request.error;
NSLog(@"请求出错:%@",error);
}
用block实现:
ASIHTTPRequest *httpRequest=[ASIHTTPRequest requestWithURL:url];
[httpRequest setRequestMethod:@"GET"];
[httpRequest setTimeOutSeconds:60];
//httpRequest.delegate=self;
[httpRequest setCompletionBlock:^{
UIImage *image=[UIImage imageWithData:httpRequest.responseData];
self.image=image;
}];
[httpRequest setFailedBlock:^{
NSError *error=httpRequest.error;
NSLog(@"请求出错:%@",error);
}];
[httpRequest startAsynchronous];
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;
第四、缓存策略
NSString *cathPath=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
ASIDownloadCache *cache=[[ASIDownloadCachealloc]init];
[cache setStoragePath:cathPath];
cache.defaultCachePolicy=ASIOnlyLoadIfNotCachedCachePolicy;
//持久缓存,一直保存在本地
httpRequest.cacheStoragePolicy = ASICachePermanentlyCacheStoragePolicy;
httpRequest.downloadCache=cache;
[httpRequest startAsynchronous];
//监听数据的来源
if (httpRequest.didUseCachedResponse) {
NSLog(@"data is from cache");
}else
{
NSLog(@"data is form net");
}