宽容他人,放过自己。

URL转码

Posted on By anchoriteFili

object-c

NSString *string = @"上海";
string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",string);
NSString *string = @"http://www.summermobi.com/sports/invite/?uname=伪球迷&uid=10003&img=http://img.summermobi.com/picture/big/jpg";

    NSString *partUrlUTF = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)string,NULL,CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"),kCFStringEncodingUTF8));
    
    NSLog(@"%@",partUrlUTF);

Swift

 转码过程

let str: String = "https://anchoritefili.github.io/2015/08/17/微信支付demo分析/"
print("urlHostAllowed + \(str.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!)")
print("urlPathAllowed + \(str.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!)")
print("urlUserAllowed + \(str.addingPercentEncoding(withAllowedCharacters: .urlUserAllowed)!)")
print("urlQueryAllowed + \(str.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)")
print("urlUserAllowed + \(str.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)")

结果:

urlHostAllowed + https%3A%2F%2Fanchoritefili.github.io%2F2015%2F08%2F17%2F%E5%BE%AE%E4%BF%A1%E6%94%AF%E4%BB%98demo%E5%88%86%E6%9E%90%2F
urlPathAllowed + https%3A//anchoritefili.github.io/2015/08/17/%E5%BE%AE%E4%BF%A1%E6%94%AF%E4%BB%98demo%E5%88%86%E6%9E%90/
urlUserAllowed + https%3A%2F%2Fanchoritefili.github.io%2F2015%2F08%2F17%2F%E5%BE%AE%E4%BF%A1%E6%94%AF%E4%BB%98demo%E5%88%86%E6%9E%90%2F
urlQueryAllowed + https://anchoritefili.github.io/2015/08/17/%E5%BE%AE%E4%BF%A1%E6%94%AF%E4%BB%98demo%E5%88%86%E6%9E%90/
urlUserAllowed + https://anchoritefili.github.io/2015/08/17/%E5%BE%AE%E4%BF%A1%E6%94%AF%E4%BB%98demo%E5%88%86%E6%9E%90/

解码过程

let encodeStr = "https%3A%2F%2Fanchoritefili.github.io%2F2015%2F08%2F17%2F%E5%BE%AE%E4%BF%A1%E6%94%AF%E4%BB%98demo%E5%88%86%E6%9E%90%2F"
print("encodeStr + \(encodeStr.removingPercentEncoding)")

结果

encodeStr + Optional("https://anchoritefili.github.io/2015/08/17/微信支付demo分析/")