在iOS 程序訪問 HTTP 資源時需要對 URL 進行 Encode,比如像拼出來的 http://unmi.cc?p1=%+&sdf&p2=中文,其中的中文、特殊符號&%和空格都必須進行轉譯才能正確訪問。在Objective-C 語言中,你可以試下
1、stringByAddingPercentEncodingWithAllowedCharacters的使用
- (NSString*)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc;
來對完整的 URL(帶請求參數的)進行編碼,比如執行下面的代碼:
NSString *url=@"http://unmi.cc?p1=%+&sd &p2=中文";
NSString *encodedValue = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
上面代碼轉換出的 encodedValue 是:
http://unmi.cc?p1=%+&sd &p2=中文
可見,它不會轉換 URL 中的?%& 符號,這也正常,因爲它肯定分不出哪個& 是參數的連接符號還是參數值,你可以單獨編碼參數,然後在拼接成 URL 之前把屬性參數值中的?%& 等符號分別替換成相應的編碼。
但是我們可以多一步處理,這樣就可以通過stringByAddingPercentEncodingWithAllowedCharacters也實現把?%& 轉換爲UTF-8格式,如下:
NSString *url=@"http://unmi.cc?p1=%+&sd &p2=中文";
NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:url] invertedSet]; NSString *encodedUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters]; NSLog(@"\n%@",encodedUrl);
2、CFURLCreateStringByAddingPercentEscapes的使用
NSString *param = @"%+&sd f";
// NSString *encodeValue = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)utf8Str, NULL, NULL, kCFStringEncodingUTF8 ));
NSString *encodedValue = (NSString*)CFURLCreateStringByAddingPercentEscapes(nil, (CFStringRef)param, nil,(CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8);這樣編碼出來的 encodedValue 爲 %+&sdf,對 ?%& 等符號也會編碼的。用上面的代碼對“中文” 進行編碼的結果是:中文,與前面是一致的。
我實際應用時還是這個 CFURLCreateStringByAddingPercentEscapes 方法比較方便。