1 #import "ViewController.h" 2 #import "Header.h" 3 4 @interface ViewController () <NSURLConnectionDataDelegate> 5 6 /** 7 * 用来存储数据 8 */ 9 @property (nonatomic, strong) NSMutableData *resultData; 10 11 @property (nonatomic, strong) NSMutableArray *dataArray; 12 13 @end 14 15 @implementation ViewController 16 17 // 懒加载 18 - (NSMutableArray *)dataArray { 19 20 if (!_dataArray) { 21 _dataArray = [NSMutableArray array]; 22 } 23 return _dataArray; 24 } 25 26 27 - (void)viewDidLoad { 28 [super viewDidLoad]; 29 // Do any additional setup after loading the view, typically from a nib. 30 } 31 32 33 #pragma mark - 同步get请求 34 - (IBAction)getSynchronousRequest:(UIButton *)sender { 35 36 // 1.创建URL 37 NSURL *url = [NSURL URLWithString:GET_URL]; 38 39 40 // 2.根据url创建具体的请求(使用缓存策略) 41 // 第一个参数:统一资源定位符URL 42 // 第二个参数:缓存的策略(枚举值) 43 /* 44 NSURLRequestUseProtocolCachePolicy//(基础策略) 45 NSURLRequestReloadIgnoringLocalCacheData//(忽略本地缓存) 46 NSURLRequestReturnCacheDataElseLoad//(首先使用缓存,如果没有本地缓存,才从原地址下载) 47 NSURLRequestReturnCacheDataDontLoad//(使用本地缓存,从不下载,如果本地没有缓存,则请求失败,此策略多用于离线操作) 48 NSURLRequestReloadIgnoringLocalAndRemoteCacheData//(无视任何缓存策略,无论是本地的还是远程的,总是从原地址重新下载) 49 NSURLRequestReloadRevalidatingCacheData//(如果本地缓存是有效的则不下载,其他任何情况都从原地址重新下载) 50 */ 51 // 第三个参数:设置延迟时间,如果超时请求终止 52 NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20]; 53 54 55 // 3.链接服务器【NSURLConnection在iOS9之后被弃用,在以后的开发中很少见】 56 // 参数1:请求对象 57 // 参数2:存储一些网络的请求信息【一般为包体,一般设置为nil】 58 // 参数3:错误信息 59 NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 60 61 62 // 4.进行json数据解析 63 NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; 64 NSLog(@"%@", resultDic); 65 66 } 67 68 69 70 #pragma mark - 同步post请求 71 - (IBAction)postSynchronousRequest:(UIButton *)sender { 72 73 // 1.创建url 74 NSURL *url = [NSURL URLWithString:POST_URL]; 75 76 77 // 2.创建网路请求【post请求必须初始化为可变请求,因为稍后要进行一些内容的设置】 78 NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:url]; 79 80 81 // 2.5.设置body 82 // 创建一个连接字符串(这个内容在以后的开发中接口文档都有标注) 83 NSString *dataStr = POST_BODY; 84 85 // 对连接字符串进行编码【这一步千万不能忘记】 86 NSData *postData = [dataStr dataUsingEncoding:NSUTF8StringEncoding]; 87 88 // 设置请求格式为post请求【在这里POST必须大写】 89 [mutableRequest setHTTPMethod:@"POST"]; 90 91 // 设置请求体(body) 92 [mutableRequest setHTTPBody:postData]; 93 94 95 // 3.链接服务器 96 NSData *data = [NSURLConnection sendSynchronousRequest:mutableRequest returningResponse:nil error:nil]; 97 98 99 // 4.解析数据 100 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; 101 NSLog(@"%@", dic); 102 103 } 104 105 106 @end