使用Swift中的URLComponents对“+”进行编码 [英] Encode '+' using URLComponents in Swift

查看:1086
本文介绍了使用Swift中的URLComponents对“+”进行编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我将查询参数添加到基本URL的方法:

This is how I add a query params to a base URL:

let baseURL: URL = ...
let queryParams: [AnyHashable: Any] = ...
var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false)
components?.queryItems = queryParams.map { URLQueryItem(name: $0, value: "\($1)") }
let finalURL = components?.url

如果其中一个值包含 + 符号,则会出现问题。由于某些原因,它在最终URL中未编码为%2B ,而是保持 + 。如果我自己编码并传递%2B NSURL 编码和'plus'变成%252B

The problem emerges when one of values contains a + symbol. For some reason it's not encoded to %2B in the final URL, instead it stays +. If I do encoding myself and pass %2B, NSURL encodes % and the 'plus' becomes %252B.

问题是如何才能%2B NSURL 的实例中?

The question is how can I have %2B in the instance of NSURL?

PS我知道,如果我自己构造一个查询字符串然后只是将结果传递给 NSURL 的构造函数 init,我甚至不会遇到这个问题?(字符串:)

P.S. I know, I wouldn't even have this problem if I constructed a query string myself and then simply pass a result to the NSURL's constructor init?(string:).

推荐答案

正如其他答案所指出的,+字符在
a查询字符串中有效,这也在
中说明 查询项目 文档。

As pointed out in the other answers, the "+" character is valid in a query string, this is also stated in the query​Items documentation.

另一方面,
< a href =https://www.w3.org/Addressing/URL/4_URI_Recommentations.html\"rel =noreferrer>针对URI寻址的W3C建议
说明

On the other hand, the W3C recommendations for URI addressing state that


在查询字符串中,加号被保留为空格的简写表示法。因此,必须对真正的加号进行编码。此方法用于使查询URI更容易在不允许空格的系统中传递。

Within the query string, the plus sign is reserved as shorthand notation for a space. Therefore, real plus signs must be encoded. This method was used to make query URIs easier to pass in systems which did not allow spaces.

这可以通过手动实现使用自定义字符集构建
编码查询字符串的百分比:

This can be achieved by "manually" building the percent encoded query string, using a custom character set:

let queryParams = ["foo":"a+b", "bar": "a-b", "baz": "a b"]
var components = URLComponents()

var cs = CharacterSet.urlQueryAllowed
cs.remove("+")

components.scheme = "http"
components.host = "www.example.com"
components.path = "/somepath"
components.percentEncodedQuery = queryParams.map {
    $0.addingPercentEncoding(withAllowedCharacters: cs)!
    + "=" + $1.addingPercentEncoding(withAllowedCharacters: cs)!
}.joined(separator: "&")

let finalURL = components.url
// http://www.example.com/somepath?bar=a-b&baz=a%20b&foo=a%2Bb

另一种选择是后...编码生成的
百分比编码的查询字符串中的加号字符:

Another option is to "post-encode" the plus character in the generated percent-encoded query string:

let queryParams = ["foo":"a+b", "bar": "a-b", "baz": "a b"]
var components = URLComponents()
components.scheme = "http"
components.host = "www.example.com"
components.path = "/somepath"
components.queryItems = queryParams.map { URLQueryItem(name: $0, value: $1) }
components.percentEncodedQuery = components.percentEncodedQuery?
    .replacingOccurrences(of: "+", with: "%2B")

let finalURL = components.url
print(finalURL!)
// http://www.example.com/somepath?bar=a-b&baz=a%20b&foo=a%2Bb

这篇关于使用Swift中的URLComponents对“+”进行编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆