在添加新查询Item时,NSURLComponents将%2B更改为+

时间:2016-06-21 20:31:16

标签: ios iphone xcode url nsurl

当我添加查询项时,NSURLComponents将%2B更改为+,而%7B保持不变。根据我的理解,它应该解码' +'和' {'为什么它只解码其中一个?

null

1 个答案:

答案 0 :(得分:1)

' +'字符在查询组件中是合法的,因此不需要进行百分比编码。

有些系统会使用' +'作为一个空间,需要' +'要加百分比编码的加号字符。但是,这种两阶段编码(将加号转换为%2B然后将空格转换为加号)容易出错,因为它很容易导致编码问题。如果URL被规范化,它也会中断(URL的语法规范化包括删除所有不必要的百分比编码 - 请参阅rfc3986第6.2.2.2节)。

因此,如果您因为您的代码正在与之交谈的服务器而需要该行为,那么您将自己处理这些额外的转换。这是一段代码,显示了您需要做的两种方式:

NSURLComponents components = [[NSURLComponents alloc] init];
NSArray items = [NSArray arrayWithObjects:[NSURLQueryItem queryItemWithName:@"name" value:@"Value +"], nil];
[components setQueryItems:items];
NSLog(@"URL queryItems: %@", [components queryItems]);
NSLog(@"URL string before: %@", [components string]);
// Replace all "+" in the percentEncodedQuery with "%2B" (a percent-encoded +) and then replace all "%20" (a percent-encoded space) with "+" 
components.percentEncodedQuery = [[components.percentEncodedQuery stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"] stringByReplacingOccurrencesOfString:@"%20" withString:@"+"];
NSLog(@"URL string after: %@", [components string]);
// This is the reverse if you receive a URL with a query in that form and want to parse it with queryItems 
components.percentEncodedQuery = [[components.percentEncodedQuery stringByReplacingOccurrencesOfString:@"+" withString:@"%20"] stringByReplacingOccurrencesOfString:@"%2B" withString:@"+"];
NSLog(@"URL string back: %@", [components string]);
NSLog(@"URL queryItems: %@", [components queryItems]);

输出结果为:

URL queryItems: ( " {name = name, value = Value +}" ) 
URL string before: ?name=Value%20+ 
URL string after: ?name=Value+%2B 
URL string back: ?name=Value%20+ 
URL queryItems: ( " {name = name, value = Value +}" )