您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS URL 合法化:三種 Percent Encoding 編碼方案

編輯:iOS 開發綜合

為什麼需要 URL 合法化

在 iOS 開發中,只要請求路徑裡出現中文或特殊符號,就必須先做編碼,讓 URL 變成合法字串,否則網路請求根本發不出去。最典型的場景是把一段 JSON 當成 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 = @"https://192.168.1.1:0001/getdata?";

顯然這串 JSON 裡的花括號、引號、逗號都是保留字元,直接拼接一定出問題。

先學會判斷 URL 是否合法

用 NSURL 的類方法試著生成一次即可:回傳 nil 就代表不合法。

NSString *urlStr = @"xxx";
//使用類方法直接去生成
NSURL *URL = [NSURL URLWithString:urlStr];
//若果返回NULL則不合法,反之合法
NSLog(@"URL:%@",URL);

方案一:stringByAddingPercentEscapesUsingEncoding

- (nullable NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc; // iOS2-9
- (nullable NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)enc; // 還原

這對方法做的就是 Percent Escapes 編解碼。所謂 percent-encoding,即用「%」加上數字或字母來代表 URL 中的保留字元,例如 %20 代表空格。

//非法
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];

NSLog(@"\n非法:%@\n合法:%@\n還原:%@\n",url_illegal,urlL_legal,urlStr_restore);

// 輸出結果
// 非法:(null)
// 合法:https://192.168.1.1:0001/getdata?%7B%22name%22:%22zwq%22,%22sex%22:%221%22,%22num%22:%22123456789%22%7D
// 還原:https://192.168.1.1:0001/getdata?{"name":"zwq","sex":"1","num":"123456789"}

方案二:CFURLCreateStringByAddingPercentEscapes

CFStringRef CFURLCreateStringByAddingPercentEscapes (
    CFAllocatorRef allocator,
    CFStringRef originalString,
    CFStringRef charactersToLeaveUnescaped,
    CFStringRef legalURLCharactersToBeEscaped,
    CFStringEncoding encoding );

參數說明:

  • allocator:傳 NULL 或 kCFAllocatorDefault,使用當前預設配置器。
  • originalString:待處理的 URL 字串。
  • charactersToLeaveUnescaped:不需編碼的保留字元,傳 NULL 代表全部都編。
  • legalURLCharactersToBeEscaped:需要被編碼的合法字元,傳 NULL 代表沒有。
  • encoding:編碼方式,不確定的話就用 UTF-8(kCFStringEncodingUTF8)。

官方建議前三個參數都傳 NULL 以簡化流程,更多細節可在 Xcode 文件裡搜尋此方法。

//路徑拼接
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);

這一路寫法比方案一囉嗦,但換來了可自訂「哪些保留字元不必編碼」的彈性。兩種方式都只在 iOS 2 到 iOS 9 有效,後續已被標記為廢棄,因此才有了第三種寫法。

方案三:stringByAddingPercentEncodingWithAllowedCharacters(iOS 7 之後推薦)

//編碼
- (nullable NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters NS_AVAILABLE(10_9, 7_0);
//解碼
@property (nullable, readonly, copy) NSString *stringByRemovingPercentEncoding NS_AVAILABLE(10_9, 7_0);

要點有三:兩個方法都固定使用 UTF-8;allowedCharacters 是「允許不編碼」的字元集合,也就是集合以外的字元全都会被編碼;另外,這個 API 是為單個參數設計的,不建議把整條 URL 一起丟進去編。

NSCharacterSet 已經預先分好類,用類方法就能取得各種集合:

+ (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 這套涵蓋全世界字元的編碼標準的分類體系,想知道每個類別實際包含哪些字元,可以直接查 Unicode 官方列表。

//非法
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];

NSLog(@"\n非法:%@\n合法:%@\n還原:%@\n",url_illegal,urlL_legal,urlStr_restore);

// 輸出結果
// 非法:(null)
// 合法:https://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
// 還原:https://192.168.1.1:0001/getdata?{"name":"zwq","sex":"1","num":"123456789"}

可以注意到冒號與逗號在方案三裡也被編碼了,這是因為「允許集合」只放了英數字元。實務上要允許哪些字元不被編碼,需依後端約定調整,例如 URL 查詢字串常會額外放行 ?、=、& 等分隔符。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved