使用默认的网络会话进行网络请求

来源:互联网 发布:电脑包推荐 知乎 编辑:程序博客网 时间:2024/06/02 06:24
    //1构建网络地址    NSURL *url = [NSURL URLWithString:@"http://www.weather.com.cn/data/sk/101010300.html"];    //2构建网络请求    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];    //设置网络请求方式    //GET请求    request.HTTPMethod = @"GET";    //POST请求    request.HTTPMethod = @"POST";    //设置请求头    [request setValue:<#(nullable NSString *)#> forHTTPHeaderField:<#(nonnull NSString *)#>];    //设置请求体    //1 POST请求必须设置请求体    //2 请求体数据类型为NSData    //创建请求体字符串    NSString *bodyString = @"cinema_id=1533";    //将字符串转化为NSData    request.HTTPBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding];    //设置网络请求的最大时长    request.timeoutInterval = 60;    //3构造会话的配置对象(可选)    //4通过配置对象构造网络会话    //使用系统默认的网络会话    NSURLSession *session = [NSURLSession sharedSession];    //5创建网络任务    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error){        //将响response转化为NSHTTPURLResponse对象        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;        //通过参数response        //获取状态码        //200 成功  404未找到        NSLog(@"%ld",httpResponse.statusCode);        //获取响应头        NSLog(@"%@", httpResponse.allHeaderFields);        //通过参数data获取响应体        if (data) {            //data解析以后是以字典形式储存,故用字典接受            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil][@"weatherinfo"];        }    }];    //6发起网络任务    [dataTask resume];
0 0