星五博客

iOS URLEncode/URLDecode GBK/UTF-8 完美方案

NSLog(@"测试UTF8编码=%@",
  CFURLCreateStringByAddingPercentEscapes(
  kCFAllocatorDefault,
  (CFStringRef)@"测试",
  (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
  NULL,
  kCFStringEncodingUTF8));
NSLog(@"测试UTF8解码=%@",
  CFURLCreateStringByReplacingPercentEscapesUsingEncoding(
  kCFAllocatorDefault,
  (CFStringRef)@"%E6%B5%8B%E8%AF%95",
  (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
  kCFStringEncodingUTF8));
NSLog(@"测试GBK编码=%@",
  CFURLCreateStringByAddingPercentEscapes(
  kCFAllocatorDefault,
  (CFStringRef)@"测试",
  (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
  NULL,
  kCFStringEncodingGB_18030_2000));
NSLog(@"测试GBK解码=%@",
  CFURLCreateStringByReplacingPercentEscapesUsingEncoding(
  kCFAllocatorDefault,
  (CFStringRef)@"%B2%E2%CA%D4",
  (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
  kCFStringEncodingGB_18030_2000));

输出结果:

测试UTF8编码=%E6%B5%8B%E8%AF%95
测试UTF8解码=测试
测试GBK编码=%B2%E2%CA%D4
测试GBK解码=测试


IOS