編碼和解碼URL數(shù)據(jù) <- URL會(huì)話(huà)編程指南

想要對(duì)部分URL字符串進(jìn)行百分號(hào)編碼,請(qǐng)使用NSString的stringByAddingPercentEncodingWithAllowedCharacters:方法,給URL組件或子組件傳遞合適的字符集:

  • User: URLUserAllowedCharacterSet
  • Password: URLPasswordAllowedCharacterSet
  • Host: URLHostAllowedCharacterSet
  • Path: URLPathAllowedCharacterSet
  • Fragment(片段): URLFragmentAllowedCharacterSet
  • Query(查詢(xún)): URLQueryAllowedCharacterSet

重要:不要使用stringByAddingPercentEncodingWithAllowedCharacters:來(lái)編碼整個(gè)URL字符串,因?yàn)槊總€(gè)URL組件或子組件對(duì)于有效字符都有不同的規(guī)則。

例如,想要對(duì)包含在URL片段中的UTF-8字符串進(jìn)行百分號(hào)編碼,請(qǐng)執(zhí)行如下操作:

NSString *originalString = @"color-#708090";

NSCharacterSet *allowedCharacters = [NSCharacterSet URLFragmentAllowedCharacterSet];

NSString *percentEncodedString = [originalString stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];

NSLog(@"%@", percentEncodedString"); // prints "color-%23708090"
let originalString = "color-#708090"

let allowedCharacters = NSCharacterSet.urlFragmentAllowed

let encodedString = originalString.addingPercentEncoding(withAllowedCharacters: allowedCharacters)

print(encodedString!) // prints "color-%23708090"

如果你想對(duì)URL組件進(jìn)行百分號(hào)編碼,使用NSURLComponents把URL分拆成它的組成部分,并訪問(wèn)相關(guān)的屬性。

例如,想要得到URL片段百分號(hào)編碼的UTF-8字符串值,請(qǐng)執(zhí)行以下操作:

NSURL *URL = [NSURL URLWithString:@"https://example.com/#color-%23708090"];

NSURLComponents *components = [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:NO];

NSString *fragment = components.fragment;

NSLog(@"%@", fragment); // prints "color-#708090"
let url = URL(string: "https://example.com/#color-%23708090")!

let components = URLComponents(url: url, resolvingAgainstBaseURL: true)!

let fragment = components.fragment!

print(fragment) // prints "color-#708090"
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容