// 导入头文件
import “ASIHTTPRequest.h”
// 发起一个同步请求,同步意为着线程阻塞,在主线程中使用此方法会使应用Hang住而不响应任何用户事件。所以,在应用程序设计时,大多被用在专门的子线程增加用户体验,或用异步请求代替。
- (void)grabURL:(id)sender
{
NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
// 用requestWithURL快捷方法获取ASIHTTPRequest的一个实例
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
// startSynchronous 方法启动同步访问
[request startSynchronous];
// 由于是同步请求,没有基于事件的回调方法,所以从request的error属性获取错误信息
NSError *error = [request error];
if (!error)
{
// responseString,为请求的返回NSString信息
NSString *response = [request responseString];
}
}
// 创建一个异步请求,异步请求的好处是不阻塞当前线程,但相对于同步请求略为复杂,至少要添加两个回调方法来获取异步事件。
- (void)grabURLInBackground:(id)sender
{
NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
// 设置代理,注意添加协议
[request setDelegate:self];
// 启动异步请求
[request startAsynchronous];
}
// 实现代理方法-成功
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
// Use when fetching binary data
NSData *responseData = [request responseData];
}
// 实现代理方法-失败
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
}
注意:
(1)同步请求是不能取消的;
(2)异步请求调用 [ request cancel] 来取消请求;取消的请求默认都会按请求失败处理,并调用请求失败delegate;如果不想调用delegate方法,则设置:[ request clearDelegatesAndCancel];
(3)安全的内存回收建议
request并没有retain你的delegate,所以在没有请求完的时候释放了此delegate,需要在dealloc方法里先取消所有请求,再释放请求实例,如:
- (void)dealloc
{
[request clearDelegatesAndCancel];
[request release];
...
[super dealloc];
}