原文:http://blog.csdn.net/lwjok2007/article/details/47023853
iOS 涉及网络编程的时候就需要与服务器存在httpurl 交互
如果说url中存在汉字,或者需要上传图片,那么就得考虑urlEncode(否则会出现网址不对)
同样接收到服务器返回的一些信息可能也存在同样问题,这时服务器可能会返回urlEcode,客户端就需要解码urlDecode
其实方法很简单,只需创建如下两个方法即可
编码 URLEncodedString
[objc] view plain copy
-(NSString *)URLEncodedString:(NSString *)str
{
NSString *encodedString = (NSString )
CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)str,
NULL,
(CFStringRef)@"!'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8));
return encodedString;
}
解码 URLDecodedString
[objc] view plain copy
-(NSString *)URLDecodedString:(NSString *)str
{
NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
return decodedString;
}
调用方法:
[objc] view plain copy
NSString *readyEcodeStr=@"adsfa asdfa s+asdf";//准备urlecode的字符串
NSString *ecodeStr=[self URLEncodedString:readyEcodeStr];
NSLog(@"readyEcodeStr=%@ ecodeStr=%@",readyEcodeStr,ecodeStr);
打印出来的log如下:
readyEcodeStr=adsfa asdfa s+asdf
ecodeStr=adsfa%20asdfa%20s%2Basdf