码迷,mamicode.com
首页 > Web开发 > 详细

NSURLConnection进行POST请求

时间:2015-06-29 09:55:11      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:

第一步: 遵守协议代理NSURLConnectionDataDelegate

第二步:网络请求

    //<1>将POST请求的网址转成URL
    NSURL * url = [NSURL URLWithString:PATH];
    //<2>将NSURL封装成请求对象
    //GET请求对象为NSURLRequest
    //POST请求对象为NSMutableURLRequest
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    //<3>设置当前请求方法,默认请求样式是GET请求
    [request setHTTPMethod:@"post"];//大小写都可以
    //<4>设置请求方式
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Tpye"];//第二个参数固定,第一个根据需要改变共4种类型
    //<5>拼接请求路径
    UITextField * tf1 = (UITextField *)[self.view viewWithTag:100];
    UITextField * tf2 = (UITextField *)[self.view viewWithTag:101];
    UITextField * tf3 = (UITextField *)[self.view viewWithTag:102];
    NSString * bodyStr = [NSString stringWithFormat:@"username=%@&password=%@&email=%@",tf1.text,tf2.text,tf3.text];
    //<6>设置请求长度
    //设置请求体的长度就是设置请求体NSData类型的数据长度
    //字符串转成data类型
    NSData * bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setValue:[NSString stringWithFormat:@"%d",(int)bodyData.length] forHTTPHeaderField:@"Content-length"];
    //设置请求体
    [request setHTTPBody:bodyData];
    //<8>开始异步请求
    [NSURLConnection connectionWithRequest:request delegate:self];

第三步:实现代理方法

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if (_myData == nil) {
        _myData = [[NSMutableData alloc]init];
    }
    else
    {
        _myData.length = 0;
    }
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_myData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //进行数据解析
    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:_myData options:NSJSONReadingMutableContainers error:nil];
    NSString * code = [dic objectForKey:@"code"];
    NSString * message = [dic objectForKey:@"message"];
    if ([code isEqualToString:@"registed"]) {
        NSLog(@"注册成功");
    }
    else
    {
        NSLog(@"失败:%@",message);
    }
}

 

 

NSURLConnection进行POST请求

标签:

原文地址:http://www.cnblogs.com/huoxingdeguoguo/p/4606774.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!