Believe in your own future, will thank yourself right now Sinner Yun

Sinner_Yun

POST

 

 

 

 

 

/*(http)get请求和post请求的区别:

 *1、post请求 请求地址和参数分离,比get更加安全

 *2、get请求只能获取服务器的数据不能上传文件,而post两者都可以

 *3、get请求在浏览器中字符串长度最大限制为1024,post 没有限制

 *4、post 上传文件 文件大小不能超过4G

 */

 

 

 

四种body参数的组织方式,对应四种contentType:  (一般都是用默认的第一种)

1、application/x-www-form-urlencoded   参数拼接形态:a=@"haha"&b=@"hehe"&c=@"houhou"

2、multipart/form-data   参数为文本或者二进制

3、application/json  参数为json格式

4、text/xml 参数为xml格式

 

 

 

 

【NSURLConnection POST用法】

 

 

NSURL *url = [NSURL URLWithString:urlStr];

    //post请求用NSMutableURLRequest,可变request的请求头

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

 

    //设置数据的请求方式(GET/POST)为post请求*****

    [request setHTTPMethod:@"POST"];

 

//设置请求参数的编码方式(请求头的一部分),可以缺省不写

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

 

//将参数的字符串转换成NSData

NSData *data = [@"username=111&email=33333&password=22222" dataUsingEncoding:NSUTF8StringEncoding];

 

//设置参数的长度(请求头的一部分)可以不写

[request setValue:[NSString stringWithFormat:@"%d",[data length]] forHTTPHeaderField:@"Content-Length"];

 

//将参数的data作为请求体*****

    [request setHTTPBody:data];

 

//<NSURLConnectionDataDelegate>

[NSURLConnection connectionWithRequest:request delegate:self];

 

 

 

 

 

 

【ASIFormDataRequest POST用法】

 

 

使用系统相册

 

1,找开系统相册

UIImagePickerController *ipc = [[UIImagePickerController alloc]init];//照片选择器

    ipc.delegate = self;//<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

    [self presentViewController:ipc animated:YES completion:nil];

 

 

//选择照片后触发用post上传

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{

    NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];

    NSString* urlStr = @"http://192.168.88.8/sns/my/upload_headimage.php";

    NSString* m_auth = [ud objectForKey:@"m_auth"];

 

//获取点击的图片

    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];

//将图片转化为二进制数据

    NSData* headData = UIImagePNGRepresentation(image);

    

//ASI中,进行post请求和文件上传用ASIFormDataRequest

//#import "ASIFormDataRequest.h"

    ASIFormDataRequest* request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlStr]];

 

//可以缺省不写

  [request setRequestMethod:@"POST"];

 

//普通的参数(key=value),如果有多个参数需要多次添加

    [request setPostValue:m_auth forKey:@"m_auth"];

//[request addPostValue:m_auth forKey:@"m_auth"];

 

//需要上传文件(转成的二进制数据) fileName:图片的名称,ContentType:上传的文件类型,key为文件对应的参数名称

    [request setData:headData withFileName:@"tmp.png" andContentType:@"image/png" forKey:@"headimage"];

//[request addData:headData withFileName:@"tmp.png" andContentType:@"image/png" forKey:@"headimage"];

 

//<ASIHTTPRequestDelegate>

    request.delegate = self;

    [request startAsynchronous];

    

    [picker dismissViewControllerAnimated:YES completion:nil];

}

 

//点击照片选择器右侧按钮执行

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{

    [picker dismissViewControllerAnimated:YES completion:nil];

} 

     

 

 

 

#import "LoginViewController.h"

#import "Regist.h"

#import "ASIFormDataRequest.h"

#import "HomeViewController.h"

@interface LoginViewController ()<RegistViewControllerDelegate,ASIHTTPRequestDelegate>

@property (weak, nonatomic) IBOutlet UITextField *nameTF;

@property (weak, nonatomic) IBOutlet UITextField *passTF;

 

@end

 

@implementation LoginViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

    self.navigationItem.title=@"Login";

    

    

    

}

- (IBAction)btnClick:(UIButton *)sender

{

    [self.view endEditing:YES];

    if (sender.tag==1) {

        

        //登录接口

        NSString *urlStr=@"http://10.0.8.8/sns/my/login.php";

        

        //用asi窗前post请求需要用这个类

        ASIFormDataRequest *request=[[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:urlStr]];

        

        //设置请求方式(asi使用post可以省略)

        [request setRequestMethod:@"POST"];

        

        //添加一个参数

        [request setPostValue:_nameTF.text forKey:@"username"];

        

        //又添加一个参数

        [request setPostValue:_passTF.text forKey:@"password"];

        

        request.delegate=self;

        

        //加载请求

        [request startAsynchronous];

        

    } else {

        Regist *rvc=[[Regist alloc]init];

        rvc.delegate=self;

        [self.navigationController pushViewController:rvc animated:YES];

    }

    

}

 

-(void)requestFinished:(ASIHTTPRequest *)request

{

    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:request.responseData options:0 error:nil];

    

    if ([[dic objectForKey:@"code"]isEqualToString:@"login_success"]) {

        //用户的身份标记

        NSString *mauth=[dic objectForKey:@"m_auth"];

        

        //将身份标记用mauth这个key存到ud里

        NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];

        [ud setObject:mauth forKey:@"mauth"];

        [ud synchronize];

        

        HomeViewController *hvc=[[HomeViewController alloc]init];

        [self.navigationController pushViewController:hvc animated:YES];

        

        

        return;

    }

    

    UIAlertView *av=[[UIAlertView alloc]initWithTitle:[dic objectForKey:@"code"] message:[dic objectForKey:@"message"] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];

    [av show];

}

 

-(void)requestFailed:(ASIHTTPRequest *)request

{

    NSLog(@"%s",__func__);

}

 

-(void)registSuccessWithName:(NSString *)name pass:(NSString *)pass

{

    _nameTF.text=name;

    _passTF.text=pass;

}

 

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    [self.view endEditing:YES];

}

 

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

/*

#pragma mark - Navigation

 

// In a storyboard-based application, you will often want to do a little preparation before navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

 

@end

 

 

 

 

 

 

 

 

 

 

 

 

 

#import <UIKit/UIKit.h>

 

@protocol RegistViewControllerDelegate <NSObject>

 

-(void)registSuccessWithName:(NSString *)name pass:(NSString *)pass;

 

@end

 

@interface Regist : UIViewController

@property(nonatomic,assign)id<RegistViewControllerDelegate>delegate;

@end

 

 

 

 

 

 

 

 

 

 

 

 

#import "Regist.h"

 

@interface Regist ()<NSURLConnectionDataDelegate,UIAlertViewDelegate>

{

    NSMutableData *_downloadData;

}

@property (weak, nonatomic) IBOutlet UITextField *nameTF;

@property (weak, nonatomic) IBOutlet UITextField *passTF;

@property (weak, nonatomic) IBOutlet UITextField *mailTF;

 

@end

 

@implementation Regist

 

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

    self.navigationItem.title=@"Reglist";

    _downloadData=[[NSMutableData alloc]init];

    

    

    

}

- (IBAction)saveClick:(UIButton *)sender {

    [self.view endEditing:YES];

 

    if (!_nameTF.text.length || !_passTF.text.length || !_mailTF.text.length) {

        UIAlertView *av =[[UIAlertView alloc]initWithTitle:@"Massage" message:@"Please Write things" delegate:nil cancelButtonTitle:@"Yes" otherButtonTitles: nil];

        [av show];

        return;

    }

    

    //所有参数拼接成的字符串,作为请求体

    NSString *bodyStr=[NSString stringWithFormat:@"username=%@&password=%@&email=%@",_nameTF.text,_passTF.text,_mailTF.text];

    

    //接口(网址)部分,作为请求头

    NSString *urlStr=@"http://10.0.8.8/sns/my/register.php";

    

    NSURL *url=[NSURL URLWithString:urlStr];

    

    //使用post联网需要可变的request

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:15];

    

    //设置请求方式为POST(POST/GET)

    [request setHTTPMethod:@"POST"];

    

    //设置请求体(需要把参数的字符串转化成NSData)

    [request setHTTPBody:[bodyStr dataUsingEncoding:NSUTF8StringEncoding]];

    

    //加载请求

    [NSURLConnection connectionWithRequest:request delegate:self];

    

    [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;

    

}

 

#pragma mark - NSRULConnection

 

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    _downloadData.length=0;

}

 

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    [_downloadData appendData:data];

}

 

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;

    

    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:_downloadData options:0 error:nil];

    

    UIAlertView *av=[[UIAlertView alloc]initWithTitle:[dic objectForKey:@"code"] message:[dic objectForKey:@"message"] delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];

    [av show];

    if ([[dic objectForKey:@"code"] isEqualToString:@"registered"]) {

        av.tag = 1;

    }

    [av show];

}

 

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{

    if (alertView.tag == 1) {

        [self.navigationController popToRootViewControllerAnimated:YES];

        [self.delegate registSuccessWithName:_nameTF.text pass:_passTF.text];

    } else {

        

    }

}

 

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;

    NSLog(@"%s",__func__);

}

 

 

 

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    [self.view endEditing:YES];

}

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

/*

#pragma mark - Navigation

 

// In a storyboard-based application, you will often want to do a little preparation before navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

 

@end

 

 

 

 

 

 

 

 

 

 

 

 

#import "HomeViewController.h"

#import "ASIFormDataRequest.h"

@interface HomeViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,ASIHTTPRequestDelegate>

{

    //图片选择控制器

    UIImagePickerController *_ipc;

}

@property (weak, nonatomic) IBOutlet UIImageView *headView;

 

@end

 

@implementation HomeViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

}

- (IBAction)btnClick:(UIButton *)sender {

    if (!_ipc) {

        _ipc=[[UIImagePickerController alloc]init];

    }

    _ipc.delegate=self;

    

    [self presentViewController:_ipc animated:YES completion:nil];

}

 

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{

    NSLog(@"%@",info);

    

    //将点击的图片显示到headView上

    _headView.image=[info objectForKey:UIImagePickerControllerOriginalImage];

    

    NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];

    NSString *mauth=[ud objectForKey:@"mauth"];

    

    //创建一个asi的post请求

    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://10.0.8.8/sns/my/upload_headimage.php"]];

    

    //告诉服务器,要为哪个用户上传头像

    [request setPostValue:mauth forKey:@"m_auth"];

    

    //将图片转成NSData

    NSData *imageData=UIImagePNGRepresentation(_headView.image);

    

    //将图片转成NSData,第二个参数图片名,供后台参考,第三个文件类型,图片就用image/png,最后一个参数是后台规定的参数名

    [request setData:imageData withFileName:@"2.png" andContentType:@"image/png" forKey:@"headimage"];

    

    request.delegate=self;

    [request startAsynchronous];

    

    //让对应的图片选择器退出

    [picker dismissViewControllerAnimated:YES completion:nil];

}

 

-(void)requestFinished:(ASIHTTPRequest *)request

{

    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:request.responseData options:0 error:nil];

    

    UIAlertView *av=[[UIAlertView alloc]initWithTitle:[dic objectForKey:@"code"] message:[dic objectForKey:@"message"] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];

    [av show];

}

 

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    [self.view endEditing:YES];

}

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

/*

#pragma mark - Navigation

 

// In a storyboard-based application, you will often want to do a little preparation before navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

 

@end

 

posted on 2014-04-03 20:23  Sinner_Yun  阅读(430)  评论(0编辑  收藏  举报

导航