zoukankan      html  css  js  c++  java
  • 【iOS系列】-iOS开发,GET,POST请求使用

    【iOS系列】-iOS开发,GET,POST请求使用

    步骤:

    1:实例化URL(网络资源)

    2:根据URL建立URLRequest(网络请求)
    默认为GET请求;
    对于POST请求,需要创建请求的数据体

    3:利用URLConnection发送网络请求(建立连接)

    NSURLConnection的同异请求(网络中一般使用异步请求,同步会阻塞主线程):

    同步请求: sendSynchronousRequest:returningResponse:error:
    
    异步请求: sendAsynchronousRequest:queue: completionHandler:
    

    //POST实例

    -(void)methodPost
    {
        // 1. 实例化URL
        NSURL *url = [NSURL URLWithString:@"XXXXXXX"];
        // 2. 建立URLRequest
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        // 默认就是GET请求
        request.HTTPMethod = @"POST";
        // 数据体
        NSString *str = [NSString stringWithFormat:@"username=%@&password=%@", userName, userPwd];
        // 将字符串转换成数据
        request.HTTPBody = [str dataUsingEncoding:NSUTF8StringEncoding];
        
        // 3.利用URLConnection发送网络请求,异步
        [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            
            if (connectionError == nil) {
                NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            }
        }];
    }
    

    //GET实例

    -(void)methodGet
    {
        // 1. 实例化URL
        NSString *urlStr = [NSString stringWithFormat:@"XXXXXXusername=%@&password=%@", userName, userPwd];
        NSURL *url = [NSURL URLWithString:urlStr];
        // 2. 建立URLRequest  默认就是GET请求
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
        //利用URLConnection发送网络请求
        [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            
            //请求成功
            if (connectionError == nil) {
                NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            }
        }];
    }
    

    作者:Darren

    微博:@IT_攻城师

    github:@Darren90

    博客:http://www.cnblogs.com/fengtengfei/

    欢迎您的访问...


  • 相关阅读:
    第二阶段冲刺第1天
    每周总结(5.30)
    每周总结(5.23)
    个人作业——顶会热词进程2.3
    个人作业——顶会热词进程2.2
    c#日期相关代码
    Linux服务器安装mysql
    Linux运行yum时出现/var/run/yum.pid已被锁定,PID为xxxx的另一个程序正在运行的问题解决
    【转】火狐浏览器js转换日期问题
    docker流程
  • 原文地址:https://www.cnblogs.com/fengtengfei/p/4445785.html
Copyright © 2011-2022 走看看