遇到XML-GB2312网页编码的处理方法
报的错误:encoding error : input conversion failed due to input error, bytes I/O error : encoder error
1. 把请求的数据转化成data
2.取XML文件的前40个字节
NSData * xmldata = [self.data subdataWithRange:NSMakeRange(0,40)];
3.以UTF-8编码进行解码
NSString *xmlstr = [[NSString alloc] initWithData:xmldata encoding:NSUTF8StringEncoding];
//搜索GB2312,如果找到,就把GB2312 改成 utf-8 (ps:替换字符串)
if ([xmlstr rangeOfString:@"\"GB2312\"" options:NSCaseInsensitiveSearch].location != NSNotFound)
{
NSLog(@"遇到:GB2312 encoding founded.正在把GB2312改成utf-8");
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSString *utf8str = [[NSString alloc] initWithData:self.data encoding:enc];
utf8str = [utf8str stringByReplacingOccurrencesOfString:@"\"GB2312\"" withString:@"\"utf-8\"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,40)];
//新的数据,可以进行正常解析
NSData *newData = [utf8str dataUsingEncoding:NSUTF8StringEncoding];
}
原文地址:http://www.linuxidc.com/Linux/2012-02/55254.htm