您的位置:首页 > 理论基础 > 计算机网络

NSURLConnection简单使用

2014-02-24 22:30 141 查看


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

- (void)httpAsynchronousRequest{  

  

    NSURL *url = [NSURL URLWithString:@"http://url"];  

      

    NSString *post=@"postData";  

      

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  

  

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];  

    [request setHTTPMethod:@"POST"];  

    [request setHTTPBody:postData];  

    [request setTimeoutInterval:10.0];  

      

    NSOperationQueue *queue = [[NSOperationQueue alloc]init];  

    [NSURLConnection sendAsynchronousRequest:request  

                                       queue:queue  

                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){  

                               if (error) {  

                                   NSLog(@"Httperror:%@%d", error.localizedDescription,error.code);  

                               }else{  

                                     

                                   NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];  

                                     

                                   NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];  

                                     

                                   NSLog(@"HttpResponseCode:%d", responseCode);  

                                   NSLog(@"HttpResponseBody %@",responseString);  

                               }  

                           }];  

  

      

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  objective-c 网络 url ios