[英]Encoding string arguments for URLs
我创建了一种为我构建URL的方法。
- (NSString *)urlFor:(NSString *)path arguments:(NSDictionary *)args
{
NSString *format = @"http://api.example.com/%@?version=2.0.1";
NSMutableString *url = [NSMutableString stringWithFormat:format, path];
if ([args isKindOfClass:[NSDictionary class]]) {
for (NSString *key in args) {
[url appendString:[NSString stringWithFormat:@"&%@=%@", key, [args objectForKey:key]]];
}
}
return url;
}
当我尝试构建类似下面的内容时,URL当然不会被编码。
NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
@"http://other.com", @"url",
@"ABCDEF", @"apiKey", nil];
NSLog(@"%@", [self urlFor:@"articles" arguments:args]);`
返回的值是http://api.example.com/articles?version=2.0.1&url=http://other.com&apiKey=ABCDEF应该是http://api.example.com/articles?version=2.0 .1&url = http%3A%2F%2Fother.com&apiKey = ABCDEF 。
我需要对键和值进行编码。 我搜索了一些东西,发现了CFURLCreateStringByAddingPercentEscapes和stringByAddingPercentEscapesUsingEncoding但我没有做过任何测试。
我该怎么做?
IIRC,当它们位于URL的查询部分时,应正确解释斜杠。 您是否测试过它是否仍然可以在没有编码减少的情况下工作? 否则,请执行以下操作:
if ([args isKindOfClass:[NSDictionary class]]) {
for (NSString *key in [args allKeys]) {
NSString *value = [(NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)[args objectForKey:key], NULL, CFSTR("/?&:=#"), kCFStringEncodingUTF8) autorelease];
[url appendString:[NSString stringWithFormat:@"&%@=%@", key, value]];
[value release];
}
}
return url;
请注意CFURLCreateStringByAddingPercentEscapes的第4个参数的值。
您应该考虑使用Google Toolbox for Mac的GTMNSString + URLArguments ; 它的设计正是为了这个目的。
我推荐我们的KSFileUtilities类。 那么你的例子就是:
- (NSString *)urlFor:(NSString *)path arguments:(NSDictionary *)args
{
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithDictionary:args];
[parameters setObject:@"2.0.1" forKey:@"version"];
NSURL *result = [NSURL ks_URLWithScheme:@"http"
host:@"api.example.com"
path:path
queryParameters:parameters;
return [result absoluteString];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.