iOS 自動處理 Http 請求的應答內容字元編碼

來源:互聯網
上載者:User

標籤: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 請求的應答內容字元編碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.