网编代码笔记:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
//01 创建URL地址
NSURL *url = [NSURLURLWithString:@"http://api.douban.com/v2/movie/top250"];
// NSURL *url = [NSURL URLWithString:@"http://api.douban.com/v2/movie/top250?count=1"];
//02 创建请求request(设置请求头,请求体,系统默认设置了GET请求,如果想要自己去设置,使用子类就可以)
// NSURLRequest *request = [NSURLRequest requestWithURL:url];这种也可以!
NSURLRequest *request = [[NSURLRequestalloc] initWithURL:url];
//03 创建会话对象
// NSURLSession *session = [[NSURLSession alloc] init];//不能这样创建!
NSURLSession *session = [NSURLSessionsharedSession];
//04 创建会话的数据任务
NSURLSessionDataTask *data = [sessiondataTaskWithRequest:requestcompletionHandler:^(NSData *_Nullable data,NSURLResponse * _Nullable response,NSError * _Nullable error) {
/*
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSLog(@"%@", httpResponse);
//获取状态码
NSInteger statusCode = httpResponse.statusCode;
NSLog(@"打印状态码:%li", statusCode);//200代表成功,404代表找不到网页
//获取响应头信息
NSDictionary *dic = httpResponse.allHeaderFields;
//添加对象
[dic objectForKey:@"Content-Type"];
NSLog(@"这个美丽的字典:%@", dic);
*/
//打印一下当前任务执行所在的线程
// NSLog(@"当前所在的线程:%@", [NSThread currentThread]);不在主线程,开启了新的线程执行
//解析数据
id result = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingMutableContainerserror:NULL];
NSLog(@"打印解析的数据结果:%@", result);
}];
//05 发起网络请求
[data resume];
}
@end


被折叠的 条评论
为什么被折叠?



