如何编码NSURL的查询部分

时间:2018-05-05 14:37:15

标签: ios encode nsurl

(iOS 8.0 +)

我想使用NSURL在查询部分传递一些参数,如下所示:

NSURLComponents *components = [[NSURLComponents alloc] initWithString:@"ft://market/detail"];
NSDictionary *parameters = @{@"username" : @"高高高", @"from" : @"中国北京"};
NSMutableArray *items = [[NSMutableArray alloc] init];
for (NSString *key in parameters.allKeys) {
    [items addObject:[[NSURLQueryItem alloc] initWithName:key value:parameters[key]]];
}
components.queryItems = items;
NSURL *url = components.URL;
NSLog(@"url : %@", url);

然而,当我收到URL并解析它时,我发现在query部分传递的中文字符是异常的,我使用NSURLComponents来解析这样的URL :

NSURLComponents *anaComponents = [NSURLComponents componentsWithString:url.absoluteString];
NSMutableDictionary *queryParams = [[NSMutableDictionary alloc] init];
for (NSURLQueryItem *querItem in anaComponents.queryItems) {
    [queryParams setObject:querItem.value forKey:querItem.name];
}
NSLog(@"queryParams : %@", queryParams);

以下是调试日志:

url : ft://market/detail?username=%E9%AB%98%E9%AB%98%E9%AB%98&from=%E4%B8%AD%E5%9B%BD%E5%8C%97%E4%BA%AC
queryParams : {
    from = "\U4e2d\U56fd\U5317\U4eac";
    username = "\U9ad8\U9ad8\U9ad8";
}

现在的问题似乎是汉字等字符的编码和解码存在问题,即使使用[parameters[key] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]方法对查询值进行编码,解码时仍然是错误的。

我要解析的查询部分如下:@{@"username" : @"高高高", @"from" : @"中国北京"};

希望你的帮助,真诚的谢谢。

0 个答案:

没有答案
相关问题