美文网首页
使用URLSession进程GET请求

使用URLSession进程GET请求

作者: kikido | 来源:发表于2016-06-11 20:14 被阅读100次

    构建URL网络地址

    NSURL *url = [NSURL URLWithString:@"http://www.weather.com.cn/data/sk/101010300.html"];
    

    构建网络请求对象 NSURLRequest

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    
    //设置请求方式 GET
    request.HTTPMethod = @"GET";
    
    //设置请求的超时时间
    request.timeoutInterval = 60;
    
    //请求头
    [request setValue:<#(nullable NSString *)#> forHTTPHeaderField:<#(nonnull NSString *)#>];
    
    //请求体
    request.HTTPBody
    
    

    通过配置对象构造网络会话 NSURLSession

    NSURLSession *session = [NSURLSession sharedSession];
    

    创建网络任务 NSURLSessionTask

     NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSLog(@"网络请求完成");
            
            //获取响应头
            //将响应对象 转化为NSHTTPURLResponse对象
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            //获取网络连接的状态码
            //  200 成功  404 网页未找到
            NSLog(@"状态码:%li", httpResponse.statusCode);
            if (httpResponse.statusCode == 200) {
                NSLog(@"请求成功");
            }
            //请求头
            NSLog(@"响应头:%@", httpResponse.allHeaderFields);
            //获取响应体
            //对响应体进行JSON解析
            if (data) {
                
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil][@"weatherinfo"];
    //            NSLog(@"响应体数据:%@", dic);
                NSArray *array = dic.allKeys;
                for (NSString *key in array) {
                    NSLog(@"%@:%@", key, dic[key]);
                }
            }
            
            
        }];
    

    发起网络任务

    [dataTask resume];
    

    相关文章

      网友评论

          本文标题:使用URLSession进程GET请求

          本文链接:https://www.haomeiwen.com/subject/pohedttx.html