我创建了一种为我构建网址的方法。
- (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 ,但我没有做过任何测试。
我该怎么做?
答案 0 :(得分:3)
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的第四个参数的值。
答案 1 :(得分:1)
您应该考虑使用Google Toolbox for Mac's GTMNSString+URLArguments;它的设计正是为了这个目的。
答案 2 :(得分:0)
我推荐我们的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];
}