NSURLConnection简单使用

来源:互联网 发布:淘宝网店出售偷拍设备 编辑:程序博客网 时间:2024/06/05 20:48

NSURLConnection是iOS自带的网络请求,使用灵活

1.创建一个NSURL
2.通过NSURLRequest 发送
3.在通过NSURLConnection连接
e.g
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@“http://www.baidu.com”] 
                 cachePolicy:NSURLRequestUseProtocolCachePolicy 
                 timeoutInterval:60.0];         //第一个参数为请求的url  第二个参数设置缓存机制   第三个参数设置请求超时时间
NSURLConnection *theConncetion=[[NSURLConnection alloc]      
                   initWithRequest:theRequest delegate:self]; 

为了下载url的内容,程序需要提供一个delegate对象,并且至少实现下面的四个方法 
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
以上是ios2就开始支持的异步请求!!!!


iOS5以后苹果公司推出了NSURLConnection 与代码块结合的异步请求,这种方法省去了上面4个方法的实现,而是运用代码快
e.g

  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. }  

0 0
原创粉丝点击