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);
        }
    }
     
  • 相关阅读:
    【BZOJ 1069】【SCOI 2007】最大土地面积 凸包+旋转卡壳
    【POJ 2187】Beauty Contest 凸包+旋转卡壳
    1056: [HAOI2008]排名系统
    1874: [BeiJing2009 WinterCamp]取石子游戏
    1055: [HAOI2008]玩具取名
    2338: [HNOI2011]数矩形
    1060: [ZJOI2007]时态同步
    1054: [HAOI2008]移动玩具
    1053: [HAOI2007]反素数ant
    1052: [HAOI2007]覆盖问题
  • 原文地址:https://www.cnblogs.com/huoxingdeguoguo/p/4606774.html
Copyright © 2011-2022 走看看