iOS 自動處理 Http 請求的應答內容字元編碼
我們來看一下如何訪問 “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 methodNSURLResponse *response = nil;NSError *error = nil;NSData *returnedData = [NSURLConnection sendSynchronousRequest:requestreturningResponse:&responseerror:&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-problemCFStringEncoding cfEncoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)[response textEncodingName]);NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(cfEncoding); // outputNSString *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.