0

我正在使用URLQueryItem对查询值进行编码,但是当我将查询传递给URLComponent属性时,url查询键也会被编码。

var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)
urlComponents.queryItems = [URLQueryItem]()
for (key,value) in parameters {
    let queryItem = URLQueryItem(name: key,
                                 value: "\(value)".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed))
    urlComponents.queryItems?.append(queryItem)
}
print("URLComponents Query Items:\n \(urlComponents.queryItems)")
print("URLComponents URL:\n \(urlComponents.url)")

输出是:

URLComponents Query Items:
 Optional([per_page=10, filters[status]=Active])
URLComponents URL:
 Optional(https://example.com/endpoint?per_page=10&filters%5Bstatus%5D=Active)

如何防止这种情况?我不希望对查询名称进行编码。

4

1 回答 1

0

删除显式.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)调用 -URLQueryItem负责编码。

于 2020-05-29T20:01:33.700 回答