在WWDC2013中 苹果团队推出了NSURLSession (iOS 7)
网络数据请求
宏定义url
#ifndef URL_h
#define URL_h
#define GET_URL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
#define POST_URL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"
#define POST_BODY @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
#endif /* URL_h */
1 . get请求
// 1.创建URL
NSURL *url = [NSURL URLWithString:GET_URL];
// 2.创建session对象
NSURLSession *session = [NSURLSession sharedSession];
// 3.创建task请求任务
//NSURLSession是基于任务去完成相关事件的
// NSURLSessionTask 所有的任务均放在这里边
NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//4解析相关数据
if (error == nil) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@", dic);
}
}];
// 5.核心步:启动任务【千万不能忘记】
//原因:NSURLSessionTask实例任务处于挂起状态 如果不启动 不会实现BLOCK里的内容
[task resume];
2 . POST请求
//1.创建URL
NSURL *url = [NSURL URLWithString:POST_URL];
//2.创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//2.5 创建BODY
NSString *bodyString = POST_BODY;
NSData *postData = [bodyString dataUsingEncoding:NSUTF8StringEncoding] ;
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
//创建session对象
NSURLSession *session = [NSURLSession sharedSession];
//创建TASK
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//5解析
if (error == nil) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@", dict);
}
}];
[task resume];
get请求 与 post请求的区别:
1.给服务器传输数据方式不同
get:通过网址字符串
post:通过data
2.传输数据大小不同
get:网址字符串最多255字节
post:使用NSData 容量超过1G
3.安全性
get:所有传输给服务器的数据显示在网址里 类似与密码的明文输入直接可见
post:数据被换成NSData(二进制数)类似于密码的密文输入 无法直接读取