zoukankan      html  css  js  c++  java
  • NSURLConnection进行POST请求

    第一步: 遵守协议代理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);
        }
    }
     
  • 相关阅读:
    iOS开发
    Xcode
    UITextField
    iOS
    过场动画
    iOS 网络状态监听和检查,
    线程互动,GCD小应用,(功能实现并代码聚集---加载动画,弹框AlertView定时消失。)
    drawRect: 小注
    FMDB_and_Sqlite3
    UIGestureRecognizer手势。
  • 原文地址:https://www.cnblogs.com/huoxingdeguoguo/p/4606774.html
Copyright © 2011-2022 走看看