• 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);
        }
    }
     
  • 相关阅读:
    分布式版本控制系统Git-----5.Git 的push命令总结
    分布式版本控制系统Git-----4.Git 常用命令整理
    分布式版本控制系统Git-----3.图形化Tortoisegit创建本地库并且提交到远程服务器上
    分布式版本控制系统Git-----2.上传至远程仓库之基础版
    分布式版本控制系统Git-----1.Git 初识
    JavaWeb笔记03-Servlet
    JavaWeb笔记01-XML
    Emmet的html语法
    npm常用命令
    Node.js中事件的循环
  • 原文地址:https://www.cnblogs.com/huoxingdeguoguo/p/4606774.html
Copyright © 2020-2023  润新知