ASIHTTPRequest是什么?
ASIHTTPRequest是简单易用的,它封装了CFNetwork API。使得与Web服务器通信变得更简单。它是用Objective-C编写的,可以在MAC OS X和iPhone应用中使用。
它适用于执行基本的HTTP请求和互动(或者说是反馈)。ASIFormDataRequest子类可以简单的实现提交数据和文件。使用multipart/form-data
提供了以下:
一个从web服务器提交和获取数据的接口
直接下载数据到内存或者本地文件系统里
能够从本地提交文件,作为post数据的一部分。兼容HTML file input mechanism
可以访问和修改http请求和响应header
获得上传下载的进度信息
异步请求和队列,自动管理上传下载队列机制
cookie 支持
请求和响应的gzip支持
代理请求
ASIHTTPRequest设置
在iphone 项目中使用ASIHTTPRequest
1、添加一些必要的文件,复制以下文件到项目中去
ASIHTTPRquestConfig.h
ASInputStream.h
ASInputStream.m
ASIHTTPRequest.h
ASIHTTPRequest.h
ASINSStringAdditions.h
ASINSStringAdditions.m
ASIFormDataRequest.h
ASIFormDataRequest.m
ASINetworkQueue.h
ASINetworkQueue.m
iphone项目还必须包含以下文件
ASIAuthenticationDialog.h
ASIAuthenticationDialog.m
一个版本的Reachability类
添加必要的框架到项目中去
CFNetwork.framework
SystemConfiguration.framework
libz.1.2.3.dylib
配置Reachability
在iphone上,ASIHTTPRequest使用Apple的Reachability类。
Reachability有两个版本,他们都能在ASIHTTPRequest发行文件的Reachability文件夹中找到。
2.0版本是最新的办迸。如果你的项目是基于iphone os 3.x和更新的系统,你应该使用2.0版本的。包括.h和.m文件。保证在ASIHTTPRequestConfig.h文件中REACHABILITY_20_API的值为1
1.5是个老版本,它和iphone os 2.2.1-iphone os 3.0兼容。保证在ASIHTTPRequestConfig.h文件中REACHABILITY_20_API的值为0
在mac ox x项目中使用AHIHTTPRequest
为了在Mac os x项目中使用ASIHTTPRequest,你需要导入以下:
SystemConfiguration.framework + zlib
CoreService.framework
在Mac OS X上,CFNetwork 是CoreServices框架的一部分。除非你写的是基于控制台的应用程序。
ASIHTTPRequest 是一个直接在CFNetwork上做的开源项目,提供了一个比官方更方便更强大的HTTP网络传输的封装。它的特色功能如下:
1,下载的数据直接保存到内存或文件系统里
2,提供直接提交(HTTP POST)文件的API
3,可以直接访问与修改HTTP请求与响应HEADER
4,轻松获取上传与下载的进度信息
5,异步请求与队列,自动管理上传与下载队列管理机
6,认证与授权的支持
7,Cookie
8,请求与响应的GZIP
9,代理请求
下面来两个ASIHTTPRequest的小例子:
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];
}