码迷,mamicode.com
首页 > 其他好文 > 详细

NSURLConnection的异步请求方式

时间:2014-07-01 17:34:35      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   使用   

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的异步请求方式,布布扣,bubuko.com

NSURLConnection的异步请求方式

标签:des   style   blog   http   color   使用   

原文地址:http://www.cnblogs.com/samniu/p/3817744.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!