iOS 自动处理 Http 请求的应答内容字符编码
太阳火神的美丽人生 (http://blog.csdn.net/opengl_es)
本文遵循“署名-非商业用途-保持一致”创作公用协议
我们来看一下如何访问 “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.
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。