开源库:ASIHttpRequest
ASIHttpRequest 下载网址:http://github.com/pokeb/asi-http-request
依赖的5个库文件:CFNetwork, SystemConfiguration,MobileCoreServices,和libz , libxml2
//通过类方法来控制队列的执行个数,但是它一旦发送请求会被立刻执行,不能进行逻辑的控制
[ASIHTTPRequest sharedQueue].maxConcurrentOperationCount = 1;
//请求队列的初始化
// self.queue = [ASINetworkQueue queue];
//并发执行的个数
// self.queue.maxConcurrentOperationCount = 1;
//让队列执行下去,创建队列可以有我们控制他的执行逻辑顺序
//[self.queue go];
//发送异步请求
-(void)aSynchronous:(NSURL *)url
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:@"GET"];
[request setTimeOutSeconds:60];
//发送异步请求代理
// request.delegate = self;
//请求数据完成的时候调用Block
[request setCompletionBlock:^{
NSData *data = request.responseData;
UIImage *image = [UIImage imageWithData:data];
self.image = image;
if (request.didUseCachedResponse) {
NSLog(@"来至于缓存");
}else {
NSLog(@"是来至网络");
}
}];
//请求数据失败调用Block
[request setFailedBlock:^{
NSLog(@"请求数据失败");
}];
//------------------------设置缓存策略-----------
NSString *cachePath = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents"];
ASIDownloadCache *cache = [[ASIDownloadCache alloc] init];
[cache setStoragePath:cachePath];
cache.defaultCachePolicy = ASIOnlyLoadIfNotCachedCachePolicy;
//这会在每一次绘画的时候清除上一次存储的
request.cacheStoragePolicy = ASICacheForSessionDurationCacheStoragePolicy;
//这里创建持久缓存,每次要调用时直接从内存中调用
//request.cacheStoragePolicy = ASICachePermanentlyCacheStoragePolicy;
// request.downloadCache = cache;
//开始异步请求
[request startAsynchronous];
//将请求添加到队列里
//通过句柄来设置获取实例对象
// AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
// [appDelegate.queue addOperation:request];
}
//发送同步请求
-(void)synchronous:(NSURL *)url
{
// ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:@"GET"];
[request setTimeOutSeconds:60];
//设置请求头
//[request setRequestHeaders:<#(NSMutableDictionary *)#>];
//设置Cookier
// [request setRequestCookies:<#(NSMutableArray *)#>];
//发送同步请求
[request startSynchronous];
//接收是否有错误信息
NSError *error = request.error;
if (error == nil) {
NSData *data = request.responseData;
UIImage *image = [UIImage imageWithData:data];
self.image = image;
}else{
NSLog(@"发送同步请求数据出错:%@",error);
}
}
#pragma mark ---aSynchronous delegate
//完成异步请求
- (void)requestFinished:(ASIHTTPRequest *)request
{
//获取数据
NSData *data = request.responseData;
UIImage *image = [UIImage imageWithData:data];
self.image = image;
}
//异步请求失败
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = request.error;
NSLog(@"异步请求失败:%@",error);
}
其他方法: