iOS

URL 编码 iOS

URL 编码 iOS

废弃的方法1:

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

废弃的方法2:

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

正确方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- (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进行解码操作,具体开发过程中还是需要根据交互协议来。