gpt4 book ai didi

ios - NSURLComponents 在添加新查询项时将 %2B 更改为 +

转载 作者:行者123 更新时间:2023-11-29 00:52:40 32 4
gpt4 key购买 nike

当我添加一个查询项时,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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com