上一节中,介绍了ASI的基本使用,而且默认的使用方式都是Get请求方式。如有疑问,请点击这里。Get请求是从url中传递参数的,并且一般是要向服务器“索要”自己想要的数据。而Post请求,一般都是表单数据的提交,请求数据的信息在请求报文中,后台服务器接受到请求信息后,会进行相应的处理,比如:登陆操作。这一节,我就ASI中使用Post请求做一些简单的介绍。
在ASI中,进行Post请求使用的类是 ASIFormDataRequest。
Example 1:网页版163邮箱登陆。
- (void)postRequest { NSURL *url = [NSURL URLWithString:@"http://mail.163.com/"]; self.request = [ASIFormDataRequest requestWithURL:url]; [self.request setPostValue:@"username" forKey:@"your username"]; [self.request setPostValue:@"password" forKey:@"your password"]; self.request.timeOutSeconds = 10; __weak typeof(self.request) that = self.request; self.request.completionBlock= ^{ NSLog(@"data:%@",that.responseString); }; [self.request startAsynchronous]; }
Example 2:上传手机相册照片到服务器。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self uploadPictureFromAlbum]; } #pragma mark - 打开照片选择控制器(即手机中的相册) - (void)uploadPictureFromAlbum { // 1. 相册控制器 UIImagePickerController *pickerController = [[UIImagePickerController alloc] init]; // 设置代理,图片选择完毕之后所要做的事情 pickerController.delegate = self; // 2. 设置类型(照片) pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; // 2. 设置类型(拍照),然后获得拍照后的图片 //pickerController.sourceType = UIImagePickerControllerSourceTypeCamera; // 3. 弹出照片 [self presentViewController:pickerController animated:YES completion:nil]; } #pragma mark - 相片选择完成后,回调回来 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { // 1.选择图片完毕后,先关闭UIImagePickerController [picker dismissViewControllerAnimated:YES completion:nil]; // 拿到图片流对象 UIImage *image = info[UIImagePickerControllerOriginalImage]; [self uploadWithImage:image]; } #pragma mark - 上传本地相册图片,二进制对象(流对象) - (void)uploadWithImage:(UIImage *)image { NSURL *postUrl = [NSURL URLWithString:@"post site url"]; // 1.建立请求 ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:postUrl]; // 2.流的形式指定上传的文件 NSData *data = UIImagePNGRepresentation(image); [request setData:data withFileName:@"uploadfileName" andContentType:@"image/png" forKey:@"my picture"]; // 3.POST其他参数 [request setPostValue:@"Jason" forKey:@"username"]; [request setPostValue:@"123" forKey:@"password"]; // 4.发送请求 [request startAsynchronous]; // 5.监听请求 request.completionBlock = ^{ NSLog(@"上传完成"); }; }
原文地址:http://blog.csdn.net/sinat_27706697/article/details/45555785