URL合法化
iOS开发过程中,网络数据请求中带有汉字或者特殊符号需要经过编码处理,使得URL合法化之后才能进行网络请求。首先先来模拟一下URL中带有特殊字符的场景,假设需要将一段JSON字符串作为参数拼接HTTP的Get请求中,代码如下
NSDictionary *dataDic = @{@"name":@"zwq",@"sex":@"1",@"num":@"123456789"};
//NSJSONWritingPrettyPrinted处理完带有换行符
NSData *data = [NSJSONSerialization dataWithJSONObject:dataDic options:kNilOptions error:nil];
//将data转换成json格式
NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//请求路径,随便写的
NSString *baseUrl = @"http://192.168.1.1:0001/getdata?";
然后就需要对jsonStr进行PercentEscapes方式的编码。在介绍如何编码之前,先说下如何校验你的URL到底是否合法
NSString *urlStr = @"xxx";
//使用类方法直接去生成
NSURL *URL = [NSURL URLWithString:urlStr];
//若果返回NULL则不合法,反之合法
NSLog(@"URL:%@",URL);
第一种处理方式:
//编码 iOS2-9
- (nullable NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc;
//还原 iOS2-9
- (nullable NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)enc;
使用这两个方法进行PercentEscapes方式的编码和解码。Percent-encoding简单来说就是使用"%"+"数字或者字母"来代表URL中的保留字符(就行编程语言的保留字符),例如%20代表空格。示例代码如下:
//模拟数据
NSDictionary *dataDic = @{@"name":@"zwq",@"sex":@"1",@"num":@"123456789"};
//NSJSONWritingPrettyPrinted处理完带有换行符
NSData *data = [NSJSONSerialization dataWithJSONObject:dataDic options:kNilOptions error:nil];
//将data转换成json格式
NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//请求路径,随便写的
NSString *baseUrl = @"http://192.168.1.1:0001/getdata?";
//非法
NSString *urlStr_illegal = [NSString stringWithFormat:@"%@%@",baseUrl,jsonStr];
NSURL *url_illegal = [NSURL URLWithString:urlStr_illegal];
//合法
NSString *urlStr_legal = [NSString stringWithFormat:@"%@%@",baseUrl,[jsonStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL *urlL_legal = [NSURL URLWithString:urlStr_legal];
//还原
NSString *urlStr_restore = [urlStr_illegal stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//非法的NULL
NSLog(@"\n非法:%@\n合法:%@\n还原:%@\n",url_illegal,urlL_legal,urlStr_restore); 输出结果:
非法:(null)
合法:http://192.168.1.1:0001/getdata?%7B%22name%22:%22zwq%22,%22sex%22:%221%22,%22num%22:%22123456789%22%7D
还原:http://192.168.1.1:0001/getdata?{"name":"zwq","sex":"1","num":"123456789"}
第二种处理方式:
CFStringRef CFURLCreateStringByAddingPercentEscapes ( CFAllocatorRef allocator, CFStringRef originalString, CFStringRef charactersToLeaveUnescaped, CFStringRef legalURLCharactersToBeEscaped, CFStringEncoding encoding );
关于参数介绍
allocator:传NULL 或者 kCFAllocatorDefault 来使用当前默认的 allocator来生成CFSting
originalString:待处理的url字符串
charactersToLeaveUnescaped:需要编码的保留字符,传NULL表示所有的保留字符都需要编码
legalURLCharactersToBeEscaped:需要编码的合法字符,传NULL表示没有合法字符需要编码
encoding:编码方式,如果不确定就是用UTF-8 (kCFStringEncodingUTF8)
注意:1、使用范围iOS2-iOS9
2、官方建议allocator、charactersToLeaveUnescaped、legalURLCharactersToBeEscaped均传递NULL来简化整个编码过程
3、更多详情请在Xcode帮助文档中搜索该方法。
示例代码如下
NSDictionary *dataDic = @{@"name":@"zwq",@"sex":@"1",@"num":@"123456789"};
//NSJSONWritingPrettyPrinted处理完带有换行符
NSData *data = [NSJSONSerialization dataWithJSONObject:dataDic options:kNilOptions error:nil];
//将data转换成json格式
NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//请求路径,随便写的
NSString *baseUrl = @"http://192.168.1.1:0001/getdata?";
//路径拼接
NSString *urlStr_cf = [NSString stringWithFormat:@"%@%@",baseUrl,jsonStr];
//字符转换
CFStringRef originalURLString = (__bridge CFStringRef)urlStr_cf;
/**
官方建议进行的一步操作,原因:URL不是你预期的那样或者你不能够指定charactersToLeaveUnescaped(保留字符)
就上边的数据,不进行这一步处理,会默认去掉JSON中的换行,否则保留,视情况而定
*/
CFStringRef preprocessedString =
CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, originalURLString, CFSTR(""), kCFStringEncodingUTF8);
//非法
CFURLRef cf_url_illegal = CFURLCreateWithString(kCFAllocatorDefault, originalURLString, NULL);
NSURL *url_illegal = (__bridge NSURL *)cf_url_illegal;
//合法
CFStringRef urlString =
CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, preprocessedString, NULL, NULL, kCFStringEncodingUTF8);
CFURLRef cf_url_legal = CFURLCreateWithString(kCFAllocatorDefault, urlString, NULL);
NSURL *url_legal = (__bridge NSURL *)cf_url_legal;
//还原
CFStringRef urlStr_restore =
CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, urlString, CFSTR(""), kCFStringEncodingUTF8);
NSLog(@"\n非法:%@\n合法:%@\n还原:%@\n",url_illegal,url_legal,urlStr_restore);
非法:(null)
合法:http://192.168.1.1:0001/getdata?%7B%22name%22:%22zwq%22,%22sex%22:%221%22,%22num%22:%22123456789%22%7D
还原:http://192.168.1.1:0001/getdata?{"name":"zwq","sex":"1","num":"123456789"}
小结:第二种方法使用起来比第一张略微麻烦,但是可以指定需要编码过滤的保留字符,灵活性更好。以上两种方式均在iOS2-iOS9有效,之后即将废弃,下边来看下第三种处理方法iOS7之后均可使用。
第三种处理方式:
//编码
- (nullable NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters NS_AVAILABLE(10_9, 7_0);
//解码
@property (nullable, readonly, copy) NSString *stringByRemovingPercentEncoding NS_AVAILABLE(10_9, 7_0);
关于接口说明:
1、此两个方法均是使用UTF-8进行编码的
2、allowedCharacters是字符集合,指定的字符集合;也就是说除了指定的字符集之外的都会被编码替换
3、此方法是用来针对参数处理的,最好不要整个URL一起编码
其中allowedCharacters参数是NSCharacterSet类方法可以直接获取字符集(这里其实不是集合的概念,便于理解),其中做好了不同类型的字符集合的分类,如下所示
+ (NSCharacterSet *)controlCharacterSet; //Unicode General Category Cc and Cf.
+ (NSCharacterSet *)whitespaceCharacterSet; // Unicode General Category Zs and CHARACTER TABULATION (U+0009).
+ (NSCharacterSet *)whitespaceAndNewlineCharacterSet;// Unicode General Category Z*, U+000A ~ U+000D, and U+0085.
+ (NSCharacterSet *)decimalDigitCharacterSet; // Decimal Numbers.
+ (NSCharacterSet *)letterCharacterSet; // Unicode General Category L* & M*.
+ (NSCharacterSet *)lowercaseLetterCharacterSet; //Unicode General Category Ll.
+ (NSCharacterSet *)uppercaseLetterCharacterSet; // Unicode General Category Lu and Lt.
+ (NSCharacterSet *)nonBaseCharacterSet; // Unicode General Category M*.
+ (NSCharacterSet *)alphanumericCharacterSet ; //Unicode General Categories L*, M*, and N*.
+ (NSCharacterSet *)decomposableCharacterSet; //“standard decomposition” in version 3.2 of the Unicode character encoding standard.
+ (NSCharacterSet *)illegalCharacterSet; //Non-Characters or that have not yet been defined in version 3.2 of the Unicode standard.
+ (NSCharacterSet *)punctuationCharacterSet; //Unicode General Category P*.
+ (NSCharacterSet *)capitalizedLetterCharacterSet; //Unicode General Category Lt.
+ (NSCharacterSet *)symbolCharacterSet; //Unicode General Category S*.
+ (NSCharacterSet *)newlineCharacterSet; //newline characters (U+000A ~ U+000D, U+0085, U+2028, and U+2029)
[Unicode General Category](Unicode General Category)中的Unicode简单来说就是包含世界上所有字符的一种编码方式,如果直观的查看每个类别下边到底包含了哪些字符,传送门在这。
此种解决方法的示例代码如下
NSDictionary *dataDic = @{@"name":@"zwq",@"sex":@"1",@"num":@"123456789"};
//NSJSONWritingPrettyPrinted处理完带有换行符
NSData *data = [NSJSONSerialization dataWithJSONObject:dataDic options:kNilOptions error:nil];
//将data转换成json格式
NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//请求路径,随便写的
NSString *baseUrl = @"http://192.168.1.1:0001/getdata?";
//非法
NSString *urlStr_illegal = [NSString stringWithFormat:@"%@%@",baseUrl,jsonStr];
NSURL *url_illegal = [NSURL URLWithString:urlStr_illegal];
//合法
NSString *urlStr_legal = [NSString stringWithFormat:@"%@%@",baseUrl,[jsonStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]]];
NSURL *urlL_legal = [NSURL URLWithString:urlStr_legal];
//还原
NSString *urlStr_restore = [urlStr_illegal stringByRemovingPercentEncoding];
//非法的NULL
NSLog(@"\n非法:%@\n合法:%@\n还原:%@\n",url_illegal,urlL_legal,urlStr_restore);
输出结果
非法:(null)
合法:http://192.168.1.1:0001/getdata?%7B%22name%22%3A%22zwq%22%2C%22sex%22%3A%221%22%2C%22num%22%3A%22123456789%22%7D
还原:http://192.168.1.1:0001/getdata?{"name":"zwq","sex":"1","num":"123456789"}