標籤:des android style blog http io color ar os
iOS 請求 URL 返回內容的字元集編碼處理自適應
太陽火神的美麗人生 (http://blog.csdn.net/opengl_es)
本文遵循“署名-非商業用途-保持一致”創作公用協議
轉載請保留此句:太陽火神的美麗人生 - 本部落格專註於 敏捷開發及移動和物聯裝置研究:iOS、Android、Html5、Arduino、pcDuino,否則,出自本部落格的文章拒絕轉載或再轉載,謝謝合作。
我們來看一下如何訪問 “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.
iOS 自動處理 Http 請求的應答內容字元編碼