首页 > 代码库 > NSURLConnection的异步请求方式
NSURLConnection的异步请求方式
iOS5.0 SDK NSURLConnection类新增的sendAsynchronousRequest:queue:completionHandler:方法
sendAsynchronousRequest可以很容易地使用NSURLRequest接收回调,完成http通信。
1. post数据
1 - (void)httpAsynchronousRequest{ 2 3 NSURL *url = [NSURL URLWithString:@"http://url"]; 4 5 NSString *post=@"postData"; 6 7 NSData *postData =http://www.mamicode.com/ [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 8 9 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];10 [request setHTTPMethod:@"POST"];11 [request setHTTPBody:postData];12 [request setTimeoutInterval:10.0];13 14 NSOperationQueue *queue = [[NSOperationQueue alloc]init];15 [NSURLConnection sendAsynchronousRequest:request16 queue:queue17 completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){18 if (error) {19 NSLog(@"Httperror:%@%d", error.localizedDescription,error.code);20 }else{21 22 NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];23 24 NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];25 26 NSLog(@"HttpResponseCode:%d", responseCode);27 NSLog(@"HttpResponseBody %@",responseString);28 }29 }];30 31 32 }
2. 拉取图片
1 [NSURLConnection sendAsynchronousRequest: 2 [NSMutableURLRequest requestWithURL:[NSURL URLWithString:imageStr]] 3 queue:[NSOperationQueue mainQueue] 4 completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) 5 { 6 NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode]; 7 if (!error && responseCode == 200) { 8 9 UIImage *_img = [[UIImage alloc] initWithData:data];10 11 }else{12 // placeHolder image 13 }14 }];
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。