return (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, CFSTR(";:@&=+$,/?%#[]"), kCFStringEncodingUTF8);
Xcode中說,這是iOS中9.那麼過時,我怎麼使用stringByAddingPercentEncodingWithAllowedCharacters?
謝謝!
return (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, CFSTR(";:@&=+$,/?%#[]"), kCFStringEncodingUTF8);
Xcode中說,這是iOS中9.那麼過時,我怎麼使用stringByAddingPercentEncodingWithAllowedCharacters?
謝謝!
試試這個
NSString *value = @"<url>";
value = [value stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
的字符集URLQueryAllowedCharacterSet
包含了允許在URL(..?key1=value1&key2=value2
)和查詢部分中的所有字符不限於允許按鍵字符和值這樣一個查詢的。例如。 URLQueryAllowedCharacterSet
包含&
和+
,因爲這些查詢當然允許(&
分隔鍵/值對和+
裝置空間),但它們不是在這樣的查詢的一個鍵或值允許的。
考慮以下代碼:
NSString * key = "my&name";
NSString * value = "test+test";
NSString * safeKey= [key
stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet URLQueryAllowedCharacterSet]
];
NSString * safeValue= [value
stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet URLQueryAllowedCharacterSet]
];
NSString * query = [NSString stringWithFormat:@"?%@=%@", safeKey, safeValue];
query
將?my&name=test+test
,這是完全錯誤的。它定義了一個名爲my
的密鑰,該密鑰沒有值,並且其名稱爲name
的密鑰值爲test test
(+表示空格!)。
正確的查詢應該是?my%26name=test%2Btest
。
只要您只處理ASCII字符串或者只要服務器可以處理URL中的UTF-8字符(現在大多數Web服務器都這樣做),那麼您絕對必須編碼的字符數實際上相當於小而且很穩定。剛剛嘗試代碼:
NSCharacterSet * queryKVSet = [NSCharacterSet
characterSetWithCharactersInString:":/?&=;[email protected]#$()',*% "
].invertedSet;
NSString * value = ...;
NSString * valueSafe = [value
stringByAddingPercentEncodingWithAllowedCharacters:queryKVSet
];
不編碼空格,%和其他字符。最安全的方法是從'URLQueryAllowedCharacterSet'開始,並刪除鍵和值中不允許的字符,如[演示](https://stackoverflow.com/a/47790833/3046117)所示。 – supik
另一種解決方案來編碼允許URLQueryAllowedCharacterSet
那些字符,但在一個鍵或值中不允許使用(如:+
):
- (NSString *)encodeByAddingPercentEscapes {
NSMutableCharacterSet *charset = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[charset removeCharactersInString:@"!*'();:@&=+$,/?%#[]"];
NSString *encodedValue = [self stringByAddingPercentEncodingWithAllowedCharacters:charset];
return encodedValue;
}
您不必刪除'#','''','[',']'(通常不安全,不屬於'URLQueryAllowedCharacterSet')。 – supik
小心,'URLQueryAllowedCharacterSet'包含' +「字符,所以這個字符不會被編碼。然而,+字符有特殊的含義,它意味着SPACE,所以當你用這種方式編碼'test + test'時,它根本不會被編碼,但是在服務器端,它被解碼爲'test test'。 – Mecki
@Mecki所以如何從允許的字符集中排除'+'?也許'removeCharactersInString:@「+」'可以用來從這個字符集中排除'+'。 – loretoparisi
@loretoparisi我通常是這樣做的http://stackoverflow.com/a/39371482/15809畢竟有很少的字符,你絕對必須編碼,但你可以編碼所有字符,如果你喜歡。 – Mecki