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 = [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:request 16 queue:queue 17 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 }];
NSURLConnection的异步请求方式
时间: 2024-11-16 03:26:56