URL 编码 iOS

URL 编码 iOS

废弃的方法1:

NSString *aa = [@"http://URL..." stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

废弃的方法2:

- (NSString *)encodeParameter:(NSString *)originalPara {
    CFStringRef encodeParaCf = CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef)originalPara, NULL, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8);
    NSString *encodePara = (__bridge NSString *)(encodeParaCf);
    CFRelease(encodeParaCf);
    return encodePara;
}

正确方法

- (void)testURL {
    NSString *charactersToEscape = @"&?=";
    NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
    /**
     使用预置的,如果不能满足要求,则使用自定义characterSetWithCharactersInString
    NSCharacterSet *allowedCharacters = [NSCharacterSet URLHostAllowedCharacterSet];
     URLHostAllowedCharacterSet      "#%/<>?@\^`{|}
     URLFragmentAllowedCharacterSet  "#%<>[\]^`{|}
     URLPasswordAllowedCharacterSet  "#%/:<>?@[\]^`{|}
     URLPathAllowedCharacterSet      "#%;<>?[\]^`{|}
     URLQueryAllowedCharacterSet     "#%<>[\]^`{|}
     URLUserAllowedCharacterSet      "#%/:<>?@[\]^`
     **/
    NSString *encodedUrl = [@"htt://baidu.com/a.do?p1=中文&p2=http://baidu.com/a?p11=x&p12=xx" stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
    NSLog(@"%@", encodedUrl);
}

ps:

在有些时候,如果业务需要url包含签名之类的参数,大多数情况下请勿对sign等签名字段转码,除非签名验证方也对sign进行解码操作,具体开发过程中还是需要根据交互协议来。

你可能感兴趣的:(URL 编码 iOS)