Codierung von Zeichenfolgenargumenten für URLs
Ich habe eine Methode zum Erstellen von URLs für mich erstellt.
- (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;
}
Wenn ich versuche, so etwas wie unten zu erstellen, werden die URLs natürlich nicht verschlüsselt.
NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
@"http://other.com", @"url",
@"ABCDEF", @"apiKey", nil];
NSLog(@"%@", [self urlFor:@"articles" arguments:args]);`
Der zurückgegebene Wert isthttp://api.example.com/articles?version=2.0.1&url=http://other.com&apiKey=ABCDEF wann es sein solltehttp://api.example.com/articles?version=2.0.1&url=http%3A%2F%2Fother.com&apiKey=ABCDEF.
Ich muss sowohl Schlüssel als auch Wert codieren. Ich habe nach etwas gesucht und gefundenCFURLCreateStringByAddingPercentEscapes undstringByAddingPercentEscapesUsingEncoding Aber keiner der Tests, die ich gemacht habe, hat funktioniert.
Wie kann ich es tun?