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

  NSString *urlString = @"http://www.example.com?a=%7B1%2B2%7D";
  NSURLComponents *components = [NSURLComponents componentsWithString:urlString];
  NSLog(@"%@",components);
  // <NSURLComponents 0x7ffc42c19d40> {scheme = http, user = (null), password = (null), host = www.example.com,
  // port = (null), path = , query = a=%7B1%2B2%7D, fragment = (null)}
  NSURLQueryItem *queryItem = [NSURLQueryItem queryItemWithName:@"hl" value:@"en-us"];
  components.queryItems = [components.queryItems arrayByAddingObject:queryItem];
  NSLog(@"%@",components);
  // <NSURLComponents 0x7ffc42c19d40> {scheme = http, user = (null), password = (null), host = www.example.com,
  // port = (null), path = , query = a=%7B1+2%7D&hl=en-us, fragment = (null)}

最佳答案

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

某些系统使用'+'作为空格,并要求'+'加号字符进行百分比编码。但是,这种两阶段编码(将加号转换为%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 +}" )

关于ios - 添加新查询项时,NSURLComponents将%2B更改为+,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37954037/

10-10 21:50