ASIHttpRequest-发送数据(转自梦维)

原文地址:http://www.dreamingwish.com/dream-2011/powerful-asihttprequest-library-c.html

 

发送数据

设定request头

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request addRequestHeader:@"Referer" value:@"http://www.dreamingwish.com/"];

使用ASIFormDataRequest POST表单

通常数据是以’application/x-www-form-urlencoded’格式发送的,如果上传了二进制数据或者文件,那么格式将自动变为‘multipart/form-data’ 

文件中的数据是需要时才从磁盘加载,所以只要web server能处理,那么上传大文件是没有问题的。

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"Ben" forKey:@"first_name"];
[request setPostValue:@"Copsey" forKey:@"last_name"];
[request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];

数据的mime头是自动判定的,但是如果你想自定义mime头,那么这样:

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

// Upload a file on disk
[request setFile:@"/Users/ben/Desktop/ben.jpg" withFileName:@"myphoto.jpg" andContentType:@"image/jpeg"
forKey:@"photo"];

// Upload an NSData instance
[request setData:imageData withFileName:@"myphoto.jpg" andContentType:@"image/jpeg" forKey:@"photo"];

你可以使用addPostValue方法来发送相同name的多个数据(梦维:服务端会以数组方式呈现):

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:@"Ben" forKey:@"names"];
[request addPostValue:@"George" forKey:@"names"];
[request addFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photos"];
[request addData:imageData withFileName:@"george.jpg" andContentType:@"image/jpeg" forKey:@"photos"];

PUT请求、自定义POST请求

如果你想发送PUT请求,或者你想自定义POST请求,使用appendPostData: 或者 appendPostDataFromFile:

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request appendPostData:[@"This is my data" dataUsingEncoding:NSUTF8StringEncoding]];
// Default becomes POST when you use appendPostData: / appendPostDataFromFile: / setPostBody:
[request setRequestMethod:@"PUT"];

posted on 2012-10-08 15:04  kiao295338444  阅读(266)  评论(0编辑  收藏  举报

导航