gpt4 book ai didi

ios - 在 Swift 中使用 URLComponents 编码 '+'

转载 作者:IT王子 更新时间:2023-10-29 05:29:30 29 4
gpt4 key购买 nike

这是我将查询参数添加到基本 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,而是保留为 +。如果我自己编码并传递 %2BNSURL 编码 % 并且“加号”变为 %252B

问题是如何在 NSURL 的实例中包含 %2B

附言我知道,如果我自己构造一个查询字符串,然后简单地将结果传递给 NSURL 的构造函数 init?(string:),我什至不会遇到这个问题.

最佳答案

正如其他答案中所指出的,“+”字符在一个查询字符串,这也在 query​Items文档:

According to RFC 3986, the plus sign is a valid character within a query, and doesn't need to be percent-encoded. However, according to the W3C recommendations for URI addressing, the plus sign is reserved as shorthand notation for a space within a query string (for example, ?greeting=hello+world).
[...]
Depending on the implementation receiving this URL, you may need to preemptively percent-encode the plus sign character.

还有 W3C recommendations for URI addressing声明

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.

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

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

另一种选择是对生成的加号字符进行“后编码”百分比编码的查询字符串:

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

关于ios - 在 Swift 中使用 URLComponents 编码 '+',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43052657/

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