ASIHTTPRequest,是一个直接在CFNetwork上做的开源项目,提供了一个比官方更方便更强大的HTTP网络传输的封装。 特色功能如下: 1,下载的数据直接保存到内存或文件系统里 2,提供直接提交(HTTP POST)文件的API 3,可以直接访问与修改HTTP请求与响应HEADER 4,轻松获取上传与下载的进度信息 5,异步请求与队列,自动管理上传与下载队列管理机 6,认证与授权的支持 7,Cookie 8,请求与响应的GZIP 9,代理请求
下面来两个小例子:
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request start];
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
}
当你需要添加更多的请求信息时,如,添加个请求Header:
[request addRequestHeader:@"name" value:@"Jory lee"];
添加Post请求时的健值:
[request setPostValue:@"Ben" forKey:@"first_name"];
[request setPostValue:@"Copsey" forKey:@"last_name"];
[request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];
设置HTTP的授权帐号:
[request setUsername:@"username"];
[request setPassword:@"password"];
一个异步请求:
- (IBAction)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];
}
在我们数据获取的过程中,如果数据源复杂,一个请求队列是必不可少的:
- (IBAction)grabURLInTheBackground:(id)sender
{
if (![self queue]) {
[self setQueue:[[[NSOperationQueue alloc] init] autorelease]];
}
NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setDidFinishSelector:@selector(requestDone:)];
[request setDidFailSelector:@selector(requestWentWrong:)];
[[self queue] addOperation:request]; //queue is an NSOperationQueue
}
- (void)requestDone:(ASIHTTPRequest *)request
{
NSString *response = [request responseString];
}
- (void)requestWentWrong:(ASIHTTPRequest *)request
{
NSError *error = [request error];
}
援引自:http://www.cocoachina.com/bbs/read.php?tid-9455.html