在使用[NSURL URLWithString:urlString]; 生成url对象时,客户端不能正确进行网络请求,
方法1:
NSString* encodedString = [urlStringstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
方法2:
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)urlString,NULL,NULL,kCFStringEncodingUTF8);
这两种方法当urlString里含有中文时url编码是正确的,但是如果其中含有已转移的%等符号时,又会再次转义而导致错误。
CFStringRefCFURLCreateStringByAddingPercentEscapes(CFAllocatorRefallocator, CFStringRef originalString, CFStringRefcharactersToLeaveUnescaped, CFStringReflegalURLCharactersToBeEscaped, CFStringEncoding encoding);
因此做出修改,写出方法:
NSString *encodedString = (NSString *)
CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)urlString,
(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
NULL,
kCFStringEncodingUTF8);
转载来自:http://blog.csdn.net/typingios/article/details/9136005