我們來看一下如何訪問 “web service”,暫時先不考慮安全鏈接問題。本例中,我想要以穩妥的方式訪問我的博客的 RSS 種子。
Lets first look at how to access our “web service” without the security overhead. In this example I want to access the RSS feed of my blog in a secure fashion.
// our secure service :-) NSURL *server = [NSURL URLWithString:@http://www.cocoanetics.com/feed/]; NSURLRequest *request = [NSURLRequest requestWithURL:server]; // use synchronous convenience method NSURLResponse *response = nil; NSError *error = nil; NSData *returnedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if (!returnedData) { NSLog(@Error retrieving data, %@, [error localizedDescription]); return NO; } // get the correct text encoding // http://stackoverflow.com/questions/1409537/nsdata-to-nsstring-converstion-problem CFStringEncoding cfEncoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef) [response textEncodingName]); NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(cfEncoding); // output NSString *xml = [[[NSString alloc] initWithData:returnedData encoding:encoding] autorelease]; NSLog(@%@, xml);
我們通過這種方式取到了我的站點的 RSS 的 XML 。這裡有一個漂亮的技巧,不采用硬編碼 UTF8 的方式,我們從應答中獲取適當的編碼。這是一個好的習慣,你也應該在任何情況下采用它。
We get the xml of my website RSS through this. There is another nifty trick in this, instead of hard coding UTF8 we actually get the appropriate encoding straight from the response. This is a good habbit so you should adopt that in any case.