你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS 自動處理 Http 請求的應答內容字符編碼

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

編輯:IOS開發綜合

 

 

 

我們來看一下如何訪問 “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.


 

 

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved