您的位置:首页 > 移动开发 > IOS开发

iOS 03-NSURLSession类 GET与POST请求

2017-09-07 16:24 183 查看
//使用步骤:

/*
 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];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息