swift - 如何使用 NSURLComponents 将 + 编码为 %2B

标签 swift encoding nsurl url-encoding

我正在使用 NSURLComponents,但似乎无法正确编码查询值。我需要最终 URL 将 + 表示为 %2B

let baseUrl = NSURL(string: "http://www.example.com")    
let components = NSURLComponents(URL: baseUrl, resolvingAgainstBaseURL: true)
components.queryItems = [ NSURLQueryItem(name: "name", value: "abc+def") ]
XCTAssertEqual(components!.string!, "http://www.example.com?connectionToken=abc%2Bdef")

失败了!

输出等于:

http://www.example.com?connectionToken=abc+def 

http://www.example.com?connectionToken=abc%2Bdef

我已经尝试了几种变体,但我似乎根本无法让它输出 %2B

最佳答案

我的回答来自Radar 24076063解释为什么它以这种方式工作(对文本进行一些清理):

The '+' character is legal in the query component so it does not need to be percent-encoded.

Some systems use the '+' as a space and require '+' the plus character to be percent-encoded. However, that kind of two stage encoding (converting plus sign to %2B and then converting space to plus sign) is prone to errors because it easily leads to encoding problems. It also breaks if the URL is normalized (syntax normalization of URLs includes the removal of all unnecessary percent-encoding — see rfc3986 section 6.2.2.2).

So, if you need that behavior because of the server your code is talking to, you'll handle the extra transformation(s) yourself. Here's a snippet of code that shows what you need to do both ways:

NSURLComponents *components = [[NSURLComponents alloc] init];
NSArray *items = [NSArray arrayWithObjects:[NSURLQueryItem queryItemWithName:@"name" value:@"Value +"], nil];
components.queryItems = 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]);

The output is:

URL queryItems: (
    "<NSURLQueryItem 0x100502460> {name = name, value = Value +}"
)

URL string before: ?name=Value%20+

URL string after: ?name=Value+%2B

URL string back: ?name=Value%20+

URL queryItems: (
    "<NSURLQueryItem 0x1002073e0> {name = name, value = Value +}"
)

关于swift - 如何使用 NSURLComponents 将 + 编码为 %2B,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31577188/

相关文章:

swift - 从数据库中检索数据

ios - 为 "hyperlocal"应用程序获取用户位置(也处于已终止状态)的适当方法

c++ - 使用 gcc 将字符串文字的编码设置为 latin1

java - Cassandra = 内存/编码- key 占用空间(哈希/字节[]=>十六进制=>UTF16=>字节[])

ios - ERROR : BOMStream BOMStreamWithFileAndSys(int, off_t, size_t, int, char *, BomSys *): read: No such file or directory in iOS

json - 我想在 NSURL (Swift) 中的字符串中插入一个变量

swift - 从另一个 TableView 插入行

ios - 如何以编程方式选择嵌入式 View 的 Controller ?

c# - 如何读取字符串中的字符作为它们的 UTF-32 十进制值?

ios - URL初始化(字符串:relativeTo:) works wrong