简体   繁体   中英

Encoding string arguments for URLs

I created a method to build URLs for me.

- (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;
}

When I try to build something like below, the URLs aren't encoded, of course.

NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"http://other.com", @"url",
                            @"ABCDEF", @"apiKey", nil];

NSLog(@"%@", [self urlFor:@"articles" arguments:args]);`

The returned value is http://api.example.com/articles?version=2.0.1&url=http://other.com&apiKey=ABCDEF when it should be http://api.example.com/articles?version=2.0.1&url=http%3A%2F%2Fother.com&apiKey=ABCDEF .

I need to encode both key and value. I searched for something and found CFURLCreateStringByAddingPercentEscapes and stringByAddingPercentEscapesUsingEncoding but none of the tests I made worked.

How can I do it?

IIRC, slashes should be interpreted properly when they're in the query part of a URL. Did you test to see if it still works without encoded slashses? Otherwise, do something like:

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;

Note the value of the 4th argument to CFURLCreateStringByAddingPercentEscapes.

You should consider using Google Toolbox for Mac's GTMNSString+URLArguments ; it's designed for exactly this purpose.

I'd recommend our KSFileUtilities set of classes. Your example would then be:

- (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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM