簡體   English   中英

編碼URL的字符串參數

[英]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

我需要對鍵和值進行編碼。 我搜索了一些東西,發現了CFURLCreateStringByAddingPercentEscapesstringByAddingPercentEscapesUsingEncoding但我沒有做過任何測試。

我該怎么做?

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM