这是如何以安全方式添加参数的示例。长而可靠。
NSString* const kBaseURL = @"http://maps.google.com/maps/api/geocode/xml";
NSMutableDictionary *parameterDic = [NSMutableDictionary dictionary];
[parameterDic setObject:@"plaza de la puerta del sol 1, madrid, spain" forKey:@"address"];
[parameterDic setObject:@"false" forKey:@"sensor"];
NSMutableArray *parameters = [NSMutableArray array];
for (__strong NSString *name in parameterDic) {
NSString *value = [parameterDic objectForKey:name];
name = encodeToPercentEscapeString(name);
value = encodeToPercentEscapeString(value);
NSString *queryComponent = [NSString stringWithFormat:@"%@=%@", name, value];
[parameters addObject:queryComponent];
}
NSString *query = [parameters componentsJoinedByString:@"&"];
NSString *urlString = [NSString stringWithFormat:@"%@?%@", kBaseURL, query];
NSURL *url = [NSURL URLWithString:urlString];
NSLog(@"%@",url);
上面的代码调用了这个 C 函数,因为 stringByAddingPercentEscapesUsingEncoding 不会转换参数名称或值中的某些特殊字符。正如 Jesse Rusak 所指出的,请参阅Proper URL (Percent) Encoding in iOS进行讨论。
// remove CFBridgingRelease and __bridge if your code is not ARC
NSString* encodeToPercentEscapeString(NSString *string) {
return (NSString *)
CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
(__bridge CFStringRef) string,
NULL,
(CFStringRef) @"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8));
}
这打印
http://maps.google.com/maps/api/geocode/xml?sensor=false&address=plaza%20de%20la%20puerta%20del%20sol%201,%20madrid,%20spain
奖励曲目:如何解构和重建字符串:
NSString *stringUrl = @"http://www.google.com:80/a/b/c;params?m=n&o=p#fragment";
NSURL *url = [NSURL URLWithString:stringUrl];
NSLog(@"%@",stringUrl);
NSLog(@" scheme: %@",[url scheme]);
NSLog(@" host: %@",[url host]);
NSLog(@" port: %@",[url port]);
NSLog(@" path: %@",[url path]);
NSLog(@" relativePath: %@",[url relativePath]);
NSLog(@"parameterString: %@",[url parameterString]);
NSLog(@" query: %@",[url query]);
NSLog(@" fragment: %@",[url fragment]);
NSMutableString *s = [NSMutableString string];
[s appendFormat:@"%@://%@",[url scheme],[url host]];
if ([url port]!=nil){
[s appendFormat:@":%@",[url port]];
}
[s appendFormat:@"%@",[url path]];
if ([url parameterString]!=nil){
[s appendFormat:@";%@",[url parameterString]];
}
if ([url query]!=nil){
[s appendFormat:@"?%@",[url query]];
}
if ([url fragment]!=nil){
[s appendFormat:@"#%@",[url fragment]];
}
NSLog(@"%@",s);
这打印
http://www.google.com:80/a/b/c;params?m=n&o=p#fragment
scheme: http
host: www.google.com
port: 80
path: /a/b/c
relativePath: /a/b/c
parameterString: params
query: m=n&o=p
fragment: fragment