NSString自带的的方法URL encoding的编码问题

NSString *password = @"Top+Secret. ";
NSString *encoded_normal = [password stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *encoded_safer = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,  (CFStringRef)password,  NULL,  (CFStringRef)@"!*'();:@&=+$,/?%#[]",  kCFStringEncodingUTF8);
 
// output with %@ otherwise the % escapes cause strange output
NSLog(@"%@", password);
NSLog(@"%@", encoded_normal);
NSLog(@"%@", encoded_safer);
通过输出情况看,用
stringByAddingPercentEscapesUsingEncoding:方法编码时,+号没有编码,存在不encode的情况
推荐使用
CFURLCreateStringByAddingPercentEscapes()
下面是一个给NSString添加的类别,来实现encode
#import 
 
@interface NSString (Helpers)
 
// helper functions
- (NSString *) stringByUrlEncoding;
 
@end

 
 
 
 
#import "NSString+Helpers.h"
 
@implementation NSString (Helpers)
 
#pragma mark Helpers
- (NSString *) stringByUrlEncoding
{
	return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,  (CFStringRef)self,  NULL,  (CFStringRef)@"!*'();:@&=+$,/?%#[]",  kCFStringEncodingUTF8);
}
 
 
 

你可能感兴趣的:(url,encode)