iOS 03-NSURLSession类 GET与POST请求

//使用步骤:

/*

 1、创建NSURLSession的会话

 2、根据会话创建Task

 3、执行Task

 */

不废话,直接上代码。

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

    [self post];

}


-(void)post {

    //设置请求地址

    NSURL *url = [NSURL URLWithString:@"https://tieba.baidu.com/f"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    //设置请求方式

    request.HTTPMethod = @"POST";

    //设置请求体

    request.HTTPBody = [@"kw=cos" dataUsingEncoding:NSUTF8StringEncoding];

    //创建Session

    NSURLSession *session = [NSURLSession sharedSession];

    //根据会话创建任务

    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        // 打印当前线程

        NSLog(@"---%@---",[NSThread currentThread]);

        

        if (error == nil) {

            

            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

            NSLog(@"---%@---",str);

            //解析JSON数据,用字典接收

            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

        }

        

    }];

    //启动任务

    [dataTask resume];


}


-(void)dataTask {


    //设置请求地址

    NSURL *url = [NSURL URLWithString:@"https://api.seniverse.com/v3/weather/now.json?key=rj6wlseq27khpqrs&location=zunyi&language=zh-Hans&unit=c"];

    //封装一个请求类

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    //创建Session

    NSURLSession *session = [NSURLSession sharedSession];

    //根据会话创建任务

    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        // 打印当前线程

        NSLog(@"---%@---",[NSThread currentThread]);

        

        if (error == nil) {

           

        }

        /*

        //回归到主线程的几种方法

         1

                   [self performSelectorOnMainThread:(nonnull SEL) withObject:(nullable id) waitUntilDone:(BOOL)]

         2

                   dispatch_async(dispatch_get_main_queue(), ^{

        

                   });

         3

                   [[NSOperationQueue mainQueue] addOperationWithBlock:^{

        

                   }];

         */

        

    }];

    //启动任务

    [dataTask resume];


}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值