URLComponents queryItems 在突变时丢失编码百分比

2024-03-03

使用时URLComponents's queryItems我发现如果您有一个查询项,其值包含一些百分比编码字符,在我的情况下/被编码为%2F,那么如果你构造一个URLComponents对象从一个String包含此类查询项的 URL,然后更改该查询项的列表URLComponents对象,那么如果你尝试得到一个URL通过致电.url on the URLComponents对象,那么查询项就会丢失其百分比编码。

这是我在操场上测试的代码:

import UIKit

// --- Part 1 ---
print("--- Part 1 ---\n")

let startURL = "https://test.com/test.jpg?X-Test-Token=FQdzEPH%2F%2F%2F"
var components = URLComponents(string: startURL)!

if let compURL = components.url {
    print(URL(string: startURL)! == compURL) // True
    print(startURL)
    print(compURL)
}

// --- Part 2 ---
print("\n--- Part 2 ---\n")

let startURLTwo = "https://test.com/test.jpg?X-Test-Token=FQdzEPH%2F%2F%2F"
let finalURL = "https://test.com/test.jpg?X-Test-Token=FQdzEPH%2F%2F%2F&foo=bar"
var componentsTwo = URLComponents(string: startURLTwo)!

let extraQueryItem = URLQueryItem(name: "foo", value: "bar")
componentsTwo.queryItems!.append(extraQueryItem)

if let compURLTwo = componentsTwo.url {
    print(URL(string: finalURL)! == compURLTwo) // False
    print(finalURL)
    print(compURLTwo)
}

这是一张图片,可以让您更容易理解正在发生的事情:


你应该使用percentEncodedQuery如果您有一个已经进行百分比编码的查询:

let startURL = "https://test.com/test.jpg"
var components = URLComponents(string: startURL)!
components.percentEncodedQuery = "X-Test-Token=FQdzEPH%2F%2F%2F"

if let compURL = components.url {
    print(compURL)
}

或者您可以指定它未转义(并且它不会转义,因为不需要转义/查询中的字符):

let startURL = "https://test.com/test.jpg"
var components = URLComponents(string: startURL)!
components.queryItems = [URLQueryItem(name: "X-Test-Token", value: "FQdzEPH///")]

if let compURL = components.url {
    print(compURL)
}

如果你必须更新queryItems,只需确保设置percentEncodedQuery最后:

let startURL = "https://test.com/test.jpg"
let encodedQuery = "X-Test-Token=FQdzEPH%2F%2F%2F"
var components = URLComponents(string: startURL)!
components.queryItems = [URLQueryItem(name: "foo", value: "bar, baz, & qux")]
if let query = components.percentEncodedQuery {
    components.percentEncodedQuery = query + "&" + encodedQuery
} else {
    components.percentEncodedQuery = encodedQuery
}

if let compURL = components.url {
    print(compURL)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

URLComponents queryItems 在突变时丢失编码百分比 的相关文章

随机推荐