ASIHttpRequest是一款及其强劲的HTTP訪问开源项目。让简单的API完毕复杂的功能,如:异步请求,队列请求,GZIP压缩。缓存,断点续传,进度跟踪,上传文件。HTTP认证。在新版本号中,还增加了Object-C闭包Block的支持,让我们的代码更加精简灵活。
依赖的5个库:
CFNetwork
SystemCorfiguration
MobileCoreServices
和libz、libxml2
ASIHttpRequest库内容能够到 Github 开源网去下载
一、ASIHttpRequest同步请求
//同步请求
- (void)synchronous:(NSURL *)url
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:@"GET"];
[request setTimeOutSeconds:60];
//设置请求头
// [request setRequestHeaders:<#(NSMutableDictionary *)#>]
//设置cookies 保存到本地 设置登录password 下次能够不用登陆
// [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);
}
}
//异步请求
- (void)aSynchronous:(NSURL *)url
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:@"GET"];
[request setTimeOutSeconds:60];
//1.使用delegate
// request.delegate = self;
//2.使用block
[request setCompletionBlock:^{
//网络请求完毕调用的block
NSData *data = request.responseData;
self.image = [UIImage imageWithData:data];
}];
[request setFailedBlock:^{
//网络请求失败调用的block
}];
//////////////////////////////////////////////
//发送异步请求
[request startAsynchronous];
}
#pragma mark - ASIHTTPRequestdelegate
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSData *data = request.responseData;
self.image = [UIImage imageWithData:data];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSLog(@"%@",request.error);
}