iOS 通过URL网络获取XML数据的两种方式

转载于:http://blog.csdn.net/crayondeng/article/details/8738768

下面简单介绍如何通过url获取xml的两种方式。

第一种方式相对简单,使用NSData的构造函数dataWithContentsOfURL;不多解释,直接上代码咯。

  1. NSURL *url = [NSURL URLWithString:@"http://222.73.161.212/ispace2/servlet/com.lemon.xml.XmlAction"];  
  2.   
  3.  //A Boolean value that turns an indicator of network activity on or off.  
  4. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;  
  5.   
  6. NSData *xmlData = [NSData dataWithContentsOfURL:url];  
  7.   
  8. [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;  
  9.   
  10. NSString *xmlString = [[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding];  
  11.   
  12. if (xmlData == nil) {  
  13.     NSLog(@"File read failed!:%@", xmlString);  
  14. }  
  15. else {  
  16.     NSLog(@"File read succeed!:%@",xmlString);  
  17. }  

上面的  NSData *xmlData = [NSData dataWithContentsOfURL:url]; 就是获取xml的关键啦。

    注意:如果直接输出xmlData的话会是一对unicode,所以用UTF-8编码转换成是String进行输出就好啦。


第二种方式:通过NSURLConnection建立网络连接,并实现它的几个委托方法,从而获取数据。

代码如下,应该可以看懂的。

  1. @implementation ViewController {  
  2.     BOOL getXmlDone;  //是否停止获取xml数据的标志  
  3.     NSMutableData *xmlData;  //存储获得的xml数据  
  4. }  
  5.   
  6. //自定义的一个方法  
  7. - (void) getXML {  
  8.     //获取xml  
  9.     xmlData = [NSMutableData data];  
  10.       
  11.     //Clears the receiver’s cache, removing all stored cached URL responses.  
  12.     //清除接收器的缓存,删除所有存储的高速缓存的URL的响应。  
  13.     [[NSURLCache sharedURLCache] removeAllCachedResponses];  
  14.     NSURL *url = [NSURL URLWithString:@"http://222.73.161.212/ispace2/servlet/com.lemon.xml.XmlAction"];  
  15.     NSURLRequest *theRequest = [NSURLRequest requestWithURL:url];  
  16.       
  17.     //create the connection with the request and start loading the data  
  18.     NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];  
  19.     [self performSelectorOnMainThread:@selector(downloadStarted) withObject:nil waitUntilDone:NO];  
  20.     if (urlConnection != nil) {  
  21.         do {  
  22.             [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];  
  23.         } while (!getXmlDone);  
  24.     }  
  25. }  
  26.   
  27. #pragma mark NSURLConnection Delegate methods  
  28. - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {  
  29.     return nil;  
  30. }  
  31. // Forward errors to the delegate.  
  32. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {  
  33.     getXmlDone = YES;  
  34. }  
  35. // Called when a chunk of data has been downloaded.  
  36. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {  
  37.     // Append the downloaded chunk of data.  
  38.     [xmlData appendData:data];  
  39. }  
  40. - (void)connectionDidFinishLoading:(NSURLConnection *)connection {  
  41.     [self performSelectorOnMainThread:@selector(downloadEnded) withObject:nil waitUntilDone:NO];  
  42.       
  43.     getXmlDone = YES;  
  44. }  
  45. - (void)downloadStarted {  
  46.     [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;  
  47. }  
  48. - (void)downloadEnded {  
  49.     [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;  
  50. }  
  51.   
  52.   
  53.   
  54. - (void)viewDidLoad  
  55. {  
  56.     [super viewDidLoad];  
  57.     // Do any additional setup after loading the view, typically from a nib.  
  58.       
  59.     [self getXML];  
  60.     NSString *xmlString = [[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding];  
  61.     NSLog(@"data: %@",xmlString);  
  62. }  
  63.   
  64. - (void)didReceiveMemoryWarning  
  65. {  
  66.     [super didReceiveMemoryWarning];  
  67.     // Dispose of any resources that can be recreated.  
  68. }  
  69.   
  70. @end  


小结一下,第一种简单,一次性获取所有的xml数据,第二种有点复杂,当然其灵活性也更好。

要验证获取的数据的准确性的话,就点击你的url吧!http://222.73.161.212/ispace2/servlet/com.lemon.xml.XmlAction


OK,下一篇文章将会介绍如何解析xml。come on!

posted @ 2014-04-21 11:29  haotianling  阅读(362)  评论(0编辑  收藏  举报