UI 网络请求(同步GET,同步POST,异步GET,异步POST)具体操作

  1 #import "MainViewController.h"  
  2   
  3 @interface MainViewController ()<NSURLConnectionDataDelegate>  
  4   
  5 @property (nonatomic, retain)UIImageView *imageView;  
  6   
  7 @property (nonatomic, retain)NSMutableData *data;// 可变数据 Data 用于拼接每次接受来的数据块  
  8 @end  
  9   
 10 @implementation MainViewController  
 11   
 12 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
 13 {  
 14     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
 15     if (self) {  
 16         // Custom initialization  
 17     }  
 18     return self;  
 19 }  
 20   
 21 - (void)viewDidLoad  
 22 {  
 23     [super viewDidLoad];  
 24     // Do any additional setup after loading the view.  
 25     self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 280, 280)];  
 26     self.imageView.backgroundColor = [UIColor redColor];  
 27     [self.view addSubview:self.imageView];  
 28     [self.imageView release];  
 29       
 30     UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];  
 31     button1.frame = CGRectMake(20, 320, 120, 40);  
 32     button1.backgroundColor = [UIColor brownColor];  
 33     [button1 setTitle:@"同步 GET" forState:UIControlStateNormal];  
 34     [button1 addTarget:self action:@selector(buttonClicked1:) forControlEvents:UIControlEventTouchUpInside];  
 35     [self.view addSubview:button1];  
 36       
 37       
 38     UIButton *button2 = [UIButton buttonWithType:UIButtonTypeSystem];  
 39     button2.frame = CGRectMake(180, 320, 120, 40);  
 40     button2.backgroundColor = [UIColor brownColor];  
 41     [button2 setTitle:@"同步 POST" forState:UIControlStateNormal];  
 42     [button2 addTarget:self action:@selector(buttonClicked2:) forControlEvents:UIControlEventTouchUpInside];  
 43     [self.view addSubview:button2];  
 44       
 45       
 46     UIButton *button3 = [UIButton buttonWithType:UIButtonTypeSystem];  
 47     button3.frame = CGRectMake(20, 400, 120, 40);  
 48     button3.backgroundColor = [UIColor brownColor];  
 49     [button3 setTitle:@"异步 GET" forState:UIControlStateNormal];  
 50     [button3 addTarget:self action:@selector(buttonClicked3:) forControlEvents:UIControlEventTouchUpInside];  
 51     [self.view addSubview:button3];  
 52       
 53       
 54     UIButton *button4 = [UIButton buttonWithType:UIButtonTypeSystem];  
 55     button4.frame = CGRectMake(180, 400, 120, 40);  
 56     button4.backgroundColor = [UIColor brownColor];  
 57     [button4 setTitle:@"异步 POST" forState:UIControlStateNormal];  
 58     [button4 addTarget:self action:@selector(buttonClicked4:) forControlEvents:UIControlEventTouchUpInside];  
 59     [self.view addSubview:button4];  
 60       
 61 }  
 62   
 63 - (void)buttonClicked1:(UIButton *)button  
 64 {  
 65     // 同步GET  
 66     // 1.拼接网络地址  
 67     NSString *str  = @"http://cdn.gq.com.tw.s3-ap-northeast-1.amazonaws.com/userfiles/images_A1/6954/2011100658141857.jpg"  
 68     ;  
 69     // 2.将地址转化为URL对象  
 70     NSURL *url = [NSURL URLWithString:str];  
 71       
 72     // 3. 创建一个请求(request)  
 73     // 参数1: 请求地址(NSURL)  
 74     // 参数2:给请求选择一个缓存策略  
 75     // 参数3: 请求超时时间  
 76     NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];  
 77     // 4. 给请求设置 请求方式  
 78     [requset setHTTPMethod:@"GET"];  
 79     // 5. 将请求发送给服务器  
 80       
 81     // 同步连接  
 82     // 参数1:请求(request)  
 83     // 参数2:响应信息  
 84     // 参数3:错误信息  
 85     // 同步连接的方法 会一直等待 数据完整接受之后才继续执行  
 86     NSURLResponse *response = nil;  
 87     NSError *error = nil;  
 88     NSData *data = [NSURLConnection sendSynchronousRequest:requset returningResponse:&response error:&error];  
 89       
 90     //在这里获得的是完整的 data数据  
 91     NSLog(@"服务器响应信息:%@", response);  
 92       
 93     // 使用NSData数据  
 94     UIImage *image = [UIImage imageWithData:data];  
 95     self.imageView.image = image;  
 96     NSLog(@"%@", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES));  
 97   
 98 }  
 99 -(void)dealloc  
100 {  
101     [_data release];  
102     [_imageView release];  
103     [super dealloc];  
104 }  
105 - (void)buttonClicked2:(UIButton *)button  
106 {  
107     // 同步POST  
108     NSString *str = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";  
109     NSURL *url = [NSURL URLWithString:str];  
110       
111     // 创建请求  
112     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];  
113     // 设置请求方式  
114     [request setHTTPMethod:@"POST"];  
115       
116     // 产生一个body  
117     NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";  
118     NSData *data = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];  
119       
120     // 设置post请求 附带的数据  
121     [request setHTTPBody:data];  
122       
123     // 同步连接 获取内容  
124     NSURLResponse *response = nil;  
125     NSData *dataBack = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];  
126     NSLog(@"%@", response);  
127       
128     // 测试返回数据内容  
129     NSString *result = [[NSString alloc] initWithData:dataBack encoding:NSUTF8StringEncoding];  
130     NSLog(@"%@", result);  
131   
132 }  
133   
134 - (void)buttonClicked3:(UIButton *)button  
135 {  
136     // 异步  
137     // 1. 产生请求  
138     NSString *str = @"http://pic13.nipic.com/20110313/2686941_211532129160_2.jpg";  
139     NSURL *url = [NSURL URLWithString:str];  
140       
141     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];  
142       
143     [request setHTTPMethod:@"GET"];  
144       
145     // 2.建立连接  
146     // 异步联接 不会卡死界面  
147     // 参数1:设定好的请求  
148     // 参数2:设定网络请求的代理人  
149     [NSURLConnection connectionWithRequest:request delegate:self];  
150       
151       
152 }  
153 // 当收到服务器的响应信息 的时候 调用  
154 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response  
155 {  
156     // 当每次需要接受新的数据的时候 初始化data属性  
157     NSLog(@"%s", __FUNCTION__);  
158     self.data = [NSMutableData data];  
159 }  
160 // 当收到服务器发送来的 data数据块 的时候 调用  
161 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  
162 {  
163     NSLog(@"%s", __FUNCTION__);  
164     [self.data appendData:data];  
165 }  
166 // 当数据接受完毕 的时候 调用  
167 -(void)connectionDidFinishLoading:(NSURLConnection *)connection  
168 {  
169     // 调用这个方法 说明 self.data属性已经是一个完整的数据  
170     NSLog(@"%s", __FUNCTION__);  
171     UIImage *image = [UIImage imageWithData:self.data];  
172     self.imageView.image = image;  
173 }  
174 - (void)buttonClicked4:(UIButton *)button  
175 {  
176     // 异步POST  
177   
178     NSString *str = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";  
179     NSURL *url = [NSURL URLWithString:str];  
180       
181     // 创建请求  
182     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];  
183     // 设置请求方式  
184     [request setHTTPMethod:@"POST"];  
185       
186     // 设置body  
187     NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";  
188     NSData *data = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];  
189       
190     // 设置post请求 附带的数据  
191     [request setHTTPBody:data];  
192       
193       
194       
195     // 2. 连接  
196     // block 基础上的异步连接  
197       
198       
199     // 参数1:请求  
200     // 参数2:返回主线程  
201     // 参数3:  
202     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {  
203         // 当异步联接完毕 而且 请求但完整的数据(参数data)之后 才执行这个块的内容  
204           
205         // 在这个块中 写处理数据的代码 (解析/转化为image/音频/视频)  
206         NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];  
207         NSLog(@"%@", dic);  
208     }];  
209       
210 }  

 

posted @ 2016-06-06 15:36  超级马力  阅读(407)  评论(0编辑  收藏  举报