当前位置: 代码迷 >> 综合 >> [iOS]iOS 中的 url 编码问题 (转)url encode nsstring ios
  详细解决方案

[iOS]iOS 中的 url 编码问题 (转)url encode nsstring ios

热度:55   发布时间:2023-12-12 02:21:33.0

原文:http://blog.csdn.net/kesalin/article/details/6678939

NSString 的 stringByAddingPercentEscapesUsingEncoding 可以对 url 参数进行编码,但是有点小问题,不会对所有需要编码的字符都编码。我们可以通过  CFStringRef 的 

CFURLCreateStringByAddingPercentEscapes 函数来封装这个功能。代码如下:

 

[cpp]  view plain copy print ?
  1. - (NSString *)encodeToPercentEscapeString: (NSString *) input  
  2. {  
  3.     // Encode all the reserved characters, per RFC 3986  
  4.     // (<http://www.ietf.org/rfc/rfc3986.txt>)  
  5.     NSString *outputStr = (NSString *)   
  6.     CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,  
  7.                                             (CFStringRef)input,  
  8.                                             NULL,  
  9.                                             (CFStringRef)@"!*'();:@&=+$,/?%#[]",  
  10.                                             kCFStringEncodingUTF8);  
  11.     return outputStr;  
  12. }  
  13.   
  14. - (NSString *)decodeFromPercentEscapeString: (NSString *) input  
  15. {  
  16.     NSMutableString *outputStr = [NSMutableString stringWithString:input];  
  17.     [outputStr replaceOccurrencesOfString:@"+"  
  18.                                withString:@" "  
  19.                                   options:NSLiteralSearch  
  20.                                     range:NSMakeRange(0, [outputStr length])];  
  21.   
  22.     return [outputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  
  23. }  

测试代码:

 

 

[cpp]  view plain copy print ?
  1. NSString * testUrl      = @"http://search.google.com?keywords=($# it's {a*123})00!*'();:@&=+$,/?%#[]";  
  2. NSLog(@"original: %@", testUrl);  
  3.   
  4. NSString * encodeStr    = [self encodeToPercentEscapeString:testUrl];  
  5. NSLog(@"encoded: %@", encodeStr);  
  6.   
  7. NSString * encodeStr2   = [testUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  
  8. NSLog(@"encoded2:%@", encodeStr2);  
  9.   
  10. NSString * decodeStr    = [self decodeFromPercentEscapeString:encodeStr];  
  11. NSLog(@"decoded: %@", decodeStr);  

结果如下:

 

[cpp]  view plain copy print ?
  1. >> original: http://search.google.com?keywords=($# it's {a*123})00!*'();:@&=+$,/?%#[]  
  2. >> encoded:  http%3A%2F%2Fsearch.google.com%3Fkeywords%3D%28%24%23%20it%27s%20%7Ba%2A123%7D%2900%21%2A%27%28%29%3B%3A%40%26%3D%2B%24%2C%2F%3F%25%23%5B%5D  
  3. >> encoded2: http://search.google.com?keywords=($%23%20it's%20%7Ba*123%7D)00!*'();:@&=+$,/?%25%23%5B%5D  
  4. >> decoded:  http://search.google.com?keywords=($# it's {a*123})00!*'();:@&=+$,/?%#[] 
  相关解决方案