标签:
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 #pragma mark - get异步请求 33 - (IBAction)getAsynchronousRequset:(UIButton *)sender { 34 35 // 1.创建url 36 NSURL *url = [NSURL URLWithString:GET_URL]; 37 38 39 // 2.创建请求 40 NSURLRequest *request = [NSURLRequest requestWithURL:url]; 41 42 // 使用delegate实现 43 [NSURLConnection connectionWithRequest:request delegate:self]; 44 45 } 46 47 48 #pragma mark - 代理方法 49 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 50 51 // 初始化数据 52 self.resultData = [NSMutableData data]; 53 54 } 55 56 // 开始接收数据(这个方法会重复执行,得到的每段数据拼接在一起就可以了) 57 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 58 59 [self.resultData appendData:data]; 60 } 61 62 // 结束服务器 63 - (void)connectionDidFinishLoading:(NSURLConnection *)connection { 64 65 // 进行数据解析 66 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingAllowFragments error:nil]; 67 NSLog(@"%@", dic); 68 } 69 70 71 72 #pragma mark - post异步请求 73 - (IBAction)postAsynchronousRequset:(UIButton *)sender { 74 75 // 1.创建url 76 NSURL *url = [NSURL URLWithString:POST_URL]; 77 78 79 // 2.创建请求 80 NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:url]; 81 82 83 // 2.5.设置body 84 // 创建一个连接字符串(这个内容在以后的开发中接口文档都有标注) 85 NSString *dataStr = POST_BODY; 86 87 // 对连接字符串进行编码【这一步千万不能忘记】 88 NSData *postData = [dataStr dataUsingEncoding:NSUTF8StringEncoding]; 89 90 // 设置请求格式为post请求【在这里POST必须大写】 91 [mutableRequest setHTTPMethod:@"POST"]; 92 93 // 设置请求体(body) 94 [mutableRequest setHTTPBody:postData]; 95 96 // 代理方法 97 [NSURLConnection connectionWithRequest:mutableRequest delegate:self]; 98 } 99 100 101 #pragma mark - 代理方法 102 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 103 104 // 初始化数据 105 self.resultData = [NSMutableData data]; 106 107 } 108 109 // 开始接收数据(这个方法会重复执行,得到的每段数据拼接在一起就可以了) 110 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 111 112 [self.resultData appendData:data]; 113 } 114 115 // 结束服务器 116 - (void)connectionDidFinishLoading:(NSURLConnection *)connection { 117 118 // 进行数据解析 119 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingAllowFragments error:nil]; 120 NSLog(@"%@", dic); 121 } 122 123 @end
标签:
原文地址:http://www.cnblogs.com/zhizunbao/p/5482621.html